2
$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?

Nicolás Ozimica
  • 9,481
  • 5
  • 38
  • 51
William Sham
  • 12,849
  • 11
  • 50
  • 67

1 Answers1

2

You can require your file Connect.php on all of your pages, and every function that needs to use the connection can refer to the global variable $mdb2.

For example:

# In file Connect.php

<?php
$dsn="mysql://$db_username:$db_password@$db_hostname/$db_database";
$mdb2=MDB2::connect($dsn);
if (PEAR::isError($mdb2))
{
    die($mdb2->getMessage());
}


#In any other file

<?php
require_once "Connect.php";
getUser($id) {
    global $mdb2;
    $mdb2->query("SELECT ....");
}

Other solution is using a Singleton Class to access the database, so that there is a function that always returns the reference to your $mdb2 variable.

Surely, the discussion Global or Singleton for database connection? is something worth reading.

Community
  • 1
  • 1
Nicolás Ozimica
  • 9,481
  • 5
  • 38
  • 51
  • Awesome. I got it to work. For future reference. Here is how i got it to work within a class. In the __construct...put global $mdb2, given you have setup $mdb2 as a global variable – William Sham Jun 08 '11 at 23:38