Thursday, July 31, 2008

Connecting to Oracle using Pear MDB2

I am currently working on a PHP based website that needs to connect to an Oracle database. In order to connect to the database I decided to use Pear mdb2. I figured this would help if I ever needed to move to another type of database.

I have used Pear before a few times and never seemed to have much of a problem with it, however this time I was struggling to even get connected. I believe the main problem was that I was connecting to an Oracle database instead of a MySQL database (which I am more comfortable with). After a long time searching I was able to find a solution to the problem. Below is my solution that I used to connect to the Oracle database. I found a few examples of it online but it was not easy to find, hopefully this will help someone out.

/**** Code Starts Here *****/
//the connect function returns the database connection object
function connect(){

$db_user = 'username';
$db_pass = 'password';
$db_host = 'host';
$db_port = 'port_number';
$sid = 'database_name';
$type = 'oci8';

//Create a host string that tells oracle to look for
//the database name (SID) instead of the service
$host = "(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)
(HOST = $db_host)
(PORT = $db_port)))
(CONNECT_DATA =
(SID = $sid)))";

$dsn = "$type://$db_user:$db_pass@$host";

$options = array( 'emulate_database' => false );
$mdb2 =& MDB2::connect($dsn, $options);
if(PEAR::isError($mdb2)) {
die("Error while connecting : " . $mdb2->getMessage().
" **-UserInfo-** ". $mdb2->getUserinfo());
}

return $mdb2; //return the database connection object
}

?>
/**** Code Ends Here ****/

The main struggle while trying to connect was putting together the host connection string. Now that I am able to connect I have been working on calling an Oracle Stored Procedure from PEAR MDB2. So far it is proving to be a difficult task to figure out, I will post back any results. If you have any questions feel free to leave them in the comments!

2 comments:

Shane Thomas said...

Just as an update to this, I probably should have removed $mdb2->getUserinfo() from the code. It is good to use for development but should not be used in production.

Shane Thomas said...

One more thing I forgot to mention, at the top of the code I should have added require_once("MDB2.php");