Friday, February 6, 2009

Getting Started on DB2 with Apache and PHP

Many users, including myself, initially ran into difficulty in connecting with their DB2 database from their PHP applications running on an Apache web server. This calls for a quick and pain-free tutorial that will have you running and off the ground in a matter of minutes!

Here are the steps:

1) We need to add the ibm_db2.dll file to the extensions folder of the PHP installation on our machine. This ibm_db2.dll file can be downloaded from PECL, http://pecl.php.net/package/ibm_db2. For windows users, there is a PECL for windows, http://pecl4win.php.net/


2) Now we need to modify the php.ini file found inside your PHP installation to add the ibm_db2 extension. To do this, simply go through the file and where you see lines such as 'extension = blahblah.dll", add a new line, 
extension=php_ibm_db2.dll

3) If you Apache web server is not yet connected with PHP, then you also need to add some lines to the httpd.conf file in the conf directory of your Apache installation.

First, ensure the php module is loaded.  To do this, add the following line to your httpd.conf file, 
LoadModule php5_module "PHP_INSTALL_DIR/php5apache2_2.dll" 

Then add the following line to ensure php applications can run on apache, 
AddType application/x-httpd-php .php

Finally, configure the path to where your php.ini file is located, 
PHPIniDir "PHP_INSTALL_DIR"

4) Now restart your apache web server and you should be able to run php on it!  To test that you can connect to a database through PHP using the apache server, you can run the following test script (with php tags),  and modified for your database, username and password:

$dbname = "my_db";
$username = "upalh";
$password = "mypassword";

$dbconn = db2_connect($dbname, $username, $password);

if (!$dbconn) {
     echo "Failed to connect: db2_conn_errormsg()";
}
else {
echo "successfully connected";
}

If you see the 'successfully connected' message when viewing this script from your web server, then you have successfully connected to your database!

-Upal

No comments:

Post a Comment