Connect to IBM Db2 with PHP

IBM Db2 is available as a fully-managed cloud RDBMS via IBM Cloud, or as a self-managed deployment via the IBM Db2 Community Edition. Regardless of how it’s deployed, you can access it either with a native-language driver or via its REST API.

If you’re using PHP, a native driver is available as a PECL extension. Detailed installation instructions are available in the PHP IBM Db2 extension repository on GitHub.

Once you have the extension installed, connecting to the database and executing queries is both fast and simple. Here’s an example:

// configure DSN
$database = 'library';
$user = 'user';
$password = 'password';
$hostname = 'localhost';
$port = 50000;
$dsn = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;HOSTNAME=$hostname;PORT=$port;PROTOCOL=TCPIP;UID=$user;PWD=$password;";

// open connection
$db2 = db2_connect($dsn, null, null) or die('Connection failure: ' . db2_conn_errormsg());

// execute query
$query = 'SELECT FNAME, LNAME FROM authors';
$stmt = db2_prepare($db2, $query);
db2_execute($stmt, array(0));

// iterate over query result object and print
while ($author = db2_fetch_object($stmt)) {
  echo "{$author->FNAME} {$author->LNAME}\n";

The main functions here are:

  • db2_connect(), to open a connection to the server. Note that you can prepare the DSN manually, as in the example above or, if you’re running it on IBM Cloud, you can extract the DSN from the IBM Cloud VCAP_SERVICES or CE_SERVICES environment variables;
  • db2_prepare() and db2_execute(), to prepare and execute SQL statements;
  • db2_fetch_object(), to fetch a row as an object (you can also retrieve rows as indexed or associative arrays).

Of course, there’s a lot more you can do with IBM Db2 and PHP. You’ll find a complete list of available functions in the IBM Db2 section of the PHP manual.