php - 在单独的类中配置 MySQL 数据库

标签 php mysql database oop mysql-connect

是否可以在单独的类中保留所有与数据库相关的配置(主机名、用户名、密码和数据库)以及连接和选择正确数据库的功能?

我试过这样的:

class Database
{
    var $config = array(
        'username' => 'someuser',
        'password' => 'somepassword',
        'hostname' => 'some_remote_host',
        'database' => 'a_database'
    );
    function __construct() {
        $this->connect();
    }
    function connect() {
        $db = $this->config;
        $conn = mysql_connect($db['hostname'], $db['username'], $db['password']);
        if(!$conn) {
            die("Cannot connect to database server"); 
        }
        if(!mysql_select_db($db['database'])) {
            die("Cannot select database");
        }
    }
}

然后在另一个类中,我将在类中使用 __construct 函数:

require_once('database.php');
var $db_conn = new Database();

但这并没有保存连接,它最终默认为服务器本地数据库连接。还是每次执行某些数据库命令之前都必须执行数据库命令?

最佳答案

我修改了您的类(class),使其如您所期望的那样工作:

<?php
class Database
{
    var $conn = null;
    var $config = array(
        'username' => 'someuser',
        'password' => 'somepassword',
        'hostname' => 'some_remote_host',
        'database' => 'a_database'
    );

    function __construct() {
        $this->connect();
    }

    function connect() {
        if (is_null($this->conn)) {
            $db = $this->config;
            $this->conn = mysql_connect($db['hostname'], $db['username'], $db['password']);
            if(!$this->conn) {
                die("Cannot connect to database server"); 
            }
            if(!mysql_select_db($db['database'])) {
                die("Cannot select database");
            }
        }
        return $this->conn;
    }
}

用法:

$db = new Database();
$conn = $db->connect();

请注意,您可以任意多次调用 connect(),它将使用当前连接,如果不存在则创建一个。这是一件好事

另外,请注意,每次您实例化一个数据库对象(使用new)时,您将创建一个新的数据库连接。我建议您考虑将数据库类实现为 Singleton或将其存储在 Registry 中用于全局访问。

您也可以用肮脏的方式将其放入 $GLOBALS。

编辑

我冒昧地修改了您的类以实现单例模式,并遵循 PHP5 OOP 约定。

<?php
class Database
{
    protected static $_instance = null;

    protected $_conn = null;

    protected $_config = array(
        'username' => 'someuser',
        'password' => 'somepassword',
        'hostname' => 'some_remote_host',
        'database' => 'a_database'
    );

    protected function __construct() {
    }

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

    public function getConnection() {
        if (is_null($this->_conn)) {
            $db = $this->_config;
            $this->_conn = mysql_connect($db['hostname'], $db['username'], $db['password']);
            if(!$this->_conn) {
                die("Cannot connect to database server"); 
            }
            if(!mysql_select_db($db['database'])) {
                die("Cannot select database");
            }
        }
        return $this->_conn;
    }

    public function query($query) {
        $conn = $this->getConnection();
        return mysql_query($query, $conn);
    }
}

用法:

$res = Database::getInstance()->query("SELECT * FROM foo;");

$db = Database::getInstance();
$db->query("UPDATE foo");
$db->query("DELETE FROM foo");

关于php - 在单独的类中配置 MySQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1202712/

相关文章:

php - 逆 htmlentities/html_entity_decode

php - 如何在 MySQL 的 instr() 中应用通配符?

mysql - 按字符串和数字排序,首先是数字,然后是 'strings of numbers'

php - Codeigniter POST/GET 变量和 $this->input->post

mysql - NodeJS MySQL Client 不支持认证协议(protocol)

Mysql2::Error 拒绝访问用户 'root' @'localhost'(使用密码:YES)

php - 尝试让 JavaScript 触发 PHP 脚本以向表中添加一行,但它不起作用

php - 使用 file_get_contents 获取失败时的响应主体

php - 如何从表中获取最近7天的记录

php - 例如,使用 cookie 加速 web 应用程序