Ian
Ian

Reputation: 25336

PHP: Dealing With MySQL Connection Variable

What is the best way to deal with the $db_conn variable once I create a mysqli object?

I've been using

$GLOBALS['_sql'] = new mysqli(...);

But this seems dirty. The alternative that I've seen is to be constantly passing the connection var to every function that calls it, but that's a huge pain.

Upvotes: 2

Views: 1950

Answers (4)

Champo
Champo

Reputation: 3419

The way I see it, theres 3 options for passing it around.

  • A Singleton, like alex proposed.
  • Storing it in $_GLOBAL.
  • Passing it around as a parameter.

Personally, I'd go with the Singleton. Using $_GLOBAL just doesn't feel right, and passing it as a parameter is just too annoying.

Upvotes: 1

zombat
zombat

Reputation: 94147

I use a Singleton class that I usually call DatabaseManager. By making a static public method called getDB(), I never have to worry about passing the database around, as it will be available anywhere. Here's a brief stub:

class DatabaseManager
{
    private static $instance;
    private $db_connection;

    public initDBConnection($connectionInfo) {
          //make connection
    }

    public static function getInstance()
    {
        if (self::$instance == null) {
            $className = __CLASS__;
            self::$instance = new $className();
        }
        return self::$instance;
    }

    public static function getDB() 
    {
         return self::getInstance()->db_connection;
    }

}

Once you've initialized a database connection, you can simply call DatabaseManager::getDB() to get the database connection.

The beauty of this approach is that it's easily extended to manage connections to multiple databases, as well as ensuring that you never have more than one connection open to any one database. Makes your connections very efficient.

Upvotes: 5

alex
alex

Reputation: 490183

What about something like

class Db {

    public static function factory() {

         return new Db();
    }

    public function __construct() {

         // Set up DB connection here
    }

}

usage like

Db::factory()->query('DELETE FROM users WHERE active = 0');

of course you'll need to program a query method.

Upvotes: 0

Jordan Running
Jordan Running

Reputation: 106027

Have you considered taking a more object-oriented approach to your app? If your PHP code is organized into classes, then you only need to pass the database connection to the instance once (e.g. in the constructor) and then can easily access it in all of that class' methods, e.g. $this->_sql.

Upvotes: 0

Related Questions