DB2 Version 9.7 for Linux, UNIX, and Windows

Connecting to an IBM data server database with PHP (PDO)

Before you can issue SQL statements to create, update, delete, or retrieve data, you must connect to a database. You can use the PHP Data Objects (PDO) interface for PHP 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.

About this task

This procedure returns a connection object to an IBM data server database. This connection stays open until you set the PDO object to NULL, or the PHP script finishes.

Before you begin

You must set up the PHP 5.1 (or later) environment on your system and enable the PDO and PDO_IBM extensions.

Procedure

To connect to an IBM data server database:

  1. Create a connection to the database by calling the PDO constructor within a try{} block. Pass a DSN value that specifies ibm: for the PDO_IBM extension, followed by either a cataloged database name or a complete database connection string for a direct TCP/IP connection.
    • (Windows): By default, the PDO_IBM extension uses connection pooling to minimize connection resources and improve connection performance.
    • (Linux and UNIX): To create a persistent connection, pass array(PDO::ATTR_PERSISTENT => TRUE) as the driver_options (fourth) argument to the PDO constructor.
  2. Optional: Set error handling options for the PDO connection in the fourth argument to the PDO constructor:
    • By default, PDO sets an error message that can be retrieved through PDO::errorInfo() and an SQLCODE that can be retrieved through PDO::errorCode() when any error occurs; to request this mode explicitly, set PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT
    • To issue a PHP E_WARNING when any error occurs, in addition to setting the error message and SQLCODE, set PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING
    • To throw a PHP exception when any error occurs, set PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  3. Catch any exception thrown by the try{} block in a corresponding catch {} block.

    For more information about the PDO API, see http://php.net/manual/en/book.pdo.php.

Example

Connect to an IBM data server database over a persistent connection.

try { 
  $connection = new PDO("ibm:SAMPLE", "db2inst1", "ibmdb2", array(
    PDO::ATTR_PERSISTENT => TRUE, 
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
  ); 
}
catch (Exception $e) {
  echo($e->getMessage());
}

What to do next

Next, you prepare and execute SQL statements.