$dsn="mysql://$db_username:$db_password@$db_hostname/$db_database";
global $mdb2;
$mdb2=MDB2::connect($dsn);
if (PEAR::isError($mdb2))
{
die($mdb2->getMessage());
}
I do this to connect to my DB, I put this in a separate php file called Connect.php and require it on all my pages.
However, when I have to query inside a function, I will have to pass $mdb2 to the function as an argument? Is this the right way to do it.
Further, I am writing a class which will query my DB. And I have no idea what to do (I don’t wanna pass it as an argument)
Do I have to re-establish the connect everytime (ie. write a function for connection)
Can’t you make the connection persistent and global?
You can require your file
Connect.phpon all of your pages, and every function that needs to use the connection can refer to theglobalvariable$mdb2.For example:
Other solution is using a
Singleton Classto access the database, so that there is a function that always returns the reference to your$mdb2variable.Surely, the discussion Global or Singleton for database connection? is something worth reading.