简体   繁体   English

使用PDO连接数据库的功能

[英]Function to connect to database using PDO

I have to create getConnection function inside of Database class. 我必须在数据库类内部创建getConnection函数。 The function should connect to a database using PDO object and returning it. 该函数应使用PDO对象连接到数据库并返回它。 I have something like this: 我有这样的事情:

class Database {

public function getConnection() {

    $result = new PDO('mysql:host=localhost;dbname=demo', 'root', '');
        return $result;

    }

}

Is it correct? 这是正确的吗? How can i know if i'm connected to database? 我怎么知道我是否连接到数据库?

PDO will throw an exception if the connection attempt fails, so you can normalize that like this: 如果连接尝试失败,PDO将引发异常,因此您可以像这样将其标准化:

class Database {
    private $_conn = null;
    public function getConnection() {
        if (!is_null($this->_conn)) {
            return $this->_conn
        }
        $this->_conn = false;
        try {
            $this->_conn = new PDO('mysql:host=localhost;dbname=demo', 'root', '');
        } catch(PDOException $e) { }
        return $this->_conn;
    }
}
$db = new Database();
$conn = $db->getConnection();
if (!$conn) {
    die("Error connecting to the database");
}
$conn->whatever();

How can i know if i'm connected to database? 我怎么知道我是否连接到数据库?

PDO will throw an exception in case of connection error. 如果出现连接错误,PDO将引发异常。

Is it correct? 这是正确的吗?

Nope, it's not a good idea, because the method is called getConnection while in reality it creates a connection. 不,这不是一个好主意,因为该方法称为getConnection而实际上它会创建一个连接。 And a public property asks to call it in the application code, resulting multiple connections from the same script. 一个public属性要求在应用程序代码中调用它,从而导致来自同一脚本的多个连接

Besides, you should always set PDO in exception mode. 此外,您应始终将PDO设置为异常模式。 And you should set charset in DSN as well. 并且您也应该在DSN中设置字符集。

Depends on the proposed use of this function the code could be 取决于该功能的建议用法,代码可能是

protected function connect()
{
    $pdo = new PDO('mysql:host=localhost;dbname=demo;charset=utf8', 'root', '');
    $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    return $pdo;
}

if it's intended to be used only once in the constructor. 如果仅在构造函数中使用一次。

While for the getConnection() function you are bound to use a static variable ho hold the single instance of PDO. 虽然对于getConnection()函数,您必须使用静态变量来保存PDO的单个实例。

Recently I took time to compile all the common mistakes for the database wrappers in the article Your first DB wrapper's childhood deceases . 最近,我花了一些时间来整理您的第一个DB包装器的童年过时文章中有关数据库包装器的所有常见错误。 You may find this reading extremely useful. 您可能会发现此阅读非常有用。

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

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