0

What is the quickest and easiest way to make a database connection available inside a class so all the public functions in the class can access it and how do I call it inside a function?

1
  • @Kevin any database driver require this. Go figure Commented Feb 12, 2011 at 7:46

2 Answers 2

2

Save the connection handle as a class variable.

class Test
{
     public $dbh;

     public function connect($host,$username,$password,$dbname)
     {
          $this->dbh = mysql_connect($host,$username,$password); //Of course, you'd want to do some actual error checking.  Also, you can have a separate function for selecting the DB if you need to use multiple databases
          mysql_select_db($dbname,$this->dbh);  //You use $this->variable to refer to the connection handle
     }

     public function query($sql)
     {
         return mysql_query($sql,$this->dbh);
     }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Or you can use the __construct() method of the class which is called automatically whenever a new object is initialized..

class MySQLDatabase {
    private $connection;
    function __construct() {
        $this->open_connection();
    }
    public function open_connection() {
        $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
        if (!$this->connection) {
            die("Database connection failed: " . mysql_error());
        } else {
            $db_select = mysql_select_db(DB_NAME, $this->connection);
            if (!$db_select) {
                die("Database selection failed: " . mysql_error());
            }
        }
    }
    public function query($sql) {
        $result = mysql_query($sql, $this->connection);
        return $result;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.