Connect to DB2 & Run a Query with PHP Example

PHP support a way to connect to db2 database. As a matter of fact, PHP is more prefered as web scripting that connect to db2 because so many documentation on web or IBM explaining about PHP and DB2.

PHP has extension library to work against db2. You has to enable the extension at PHP.ini file. On my Win box, the line looks like this “extension=php_ibm_db2.dll”. If you see the line commented with (;) then uncomment it and restart your IIS or apache service.

Here is the example:

$database= "SAMPLE";
$user = "usernm";
$passwd = "pwd";

$conn = db2_connect($database,$user,$passwd);
if ($conn) {
   $sql = "select DEPTNO, DEPTNAME from DEPARTMENT";
   $stmt = db2_prepare($conn, $sql);
   if ($stmt) {
      $result = db2_execute($stmt);
      if (!$result) {
         echo "exec errormsg: " .db2_stmt_errormsg($stmt);
      }
      while ($row = db2_fetch_array($stmt)) {
         print "$row[0] $row[1] ";
      }
   } else {
         echo "exec errormsg: " . db2_stmt_errormsg($stmt);
   }
   db2_close($conn);
   } else {
      echo "faild ".db2_conn_errormsg();
}

db2_connect function works to make connection to db2, with parameter database, username, password which are self explanatory.

if the connection is success then you write query statement with “db2_prepare” to wrap query and execute it with “db2_execute”.

db2_fetch_array walks the entire recordset, now you can display records value.

At the end of operation, dont forget to close the connection for releasing memory and I/O resources.

Some errors might be occur because wrong connection parameter or query syntax mistakes. You can display connection and query errors with “db2_conn_errormsg()” and “db2_stmt_errormsg($stmt)” function respectively.

Note: db2_connect function use default instance that set on machine environment variables (DB2INSTANCE). To change to another instance just change the environment varible. Restart IIS or apache service, if it necessary.

If you want to know about db2 instance just view my post

Advertisements

2 responses to “Connect to DB2 & Run a Query with PHP Example

  1. Pingback: Remote DB2 Database Connection Setup | Enlightening People

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s