DB2 Version 9.7 for Linux, UNIX, and Windows

Connecting to an IBM data server database in PHP (ibm_db2)

Before you can issue SQL statements to create, update, delete, or retrieve data, you need to connect to a database from your PHP application. You can use the ibm_db2 API to connect to an IBM® data server database through either a cataloged connection or a direct TCP/IP connection. To improve performance, you can also create a persistent connection.

Before you begin

Before connecting to an IBM data server database through the ibm_db2 extension, you must set up the PHP environment on your system and enable the ibm_db2 extension.

Procedure

To return a connection resource that you can use to call SQL statements, call one of the following connection functions:
Table 1. ibm_db2 connection functions
Function Description
db2_connect Creates a non-persistent connection.
db2_pconnect Creates a persistent connection. A persistent connection remains open between PHP requests, which allows subsequent PHP script requests to reuse the connection if they have an identical set of credentials.

The database values that you pass as arguments to these functions can specify either a cataloged database name or a complete database connection string for a direct TCP/IP connection. You can specify optional arguments that control when transactions are committed, the case of the column names that are returned, and the cursor type.

If the connection attempt fails, you can retrieve diagnostic information by calling the db2_conn_error or db2_stmt_errormsg function.

When you create a connection by calling the db2_connect function, PHP closes the connection to the database when one of the following events occurs:

When you create a connection by calling the db2_pconnect function, PHP ignores any calls to the db2_close function for the specified connection resource, and keeps the connection to the database open for subsequent PHP scripts.

For more information about the ibm_db2 API, see http://www.php.net/docs.php.

Example

Connect to a cataloged database.

<?php
$database = "sample";
$user = "db2inst1";
$password = "";

$conn = db2_connect($database, $user, $password);

if ($conn) {
echo "Connection succeeded.";
db2_close($conn);
}
else {
echo "Connection failed.";
}
?> 

What to do next

If the connection attempt is successful, you can use the connection resource when you call ibm_db2 functions that execute SQL statements. Next, prepare and execute SQL statements.