PHP类中的数据库连接

时间:2011-02-12 07:38:32

标签: php

在类中使数据库连接可用的最快捷最简单的方法是什么,这样类中的所有公共函数都可以访问它,如何在函数内调用它?

2 个答案:

答案 0 :(得分:2)

将连接句柄保存为类变量。

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

答案 1 :(得分:0)

或者你可以使用类的__construct()方法,只要初始化新对象就会自动调用它。

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