Connecting to an IBM data server database in PHP (ibm_db2)
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
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 listed events occurs:
- You call the db2_close function for the connection
- You set the connection resource to NULL
- The PHP script finishes
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.