开发者

db connection in class PHP

开发者 https://www.devze.com 2023-02-09 22:02 出处:网络
What is the quickest and easiest way to make a da开发者_如何学Ctabase 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?

What is the quickest and easiest way to make a da开发者_如何学Ctabase 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?


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);
     }
}


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;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消