简体   繁体   English

PHP类中的数据库连接

[英]db connection in class PHP

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

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.. 或者您可以使用类的__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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM