简体   繁体   English

在 index.php 文件中编写数据库连接

[英]Writing a database connection in index.php file

I have a PDO connection to database in index.php file.我在index.php文件中有一个到数据库的 PDO 连接。

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";
$dbh_conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$dbh_conn->exec("set names utf8");
$dbh_conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Almost all pages of my website need database.我网站的几乎所有页面都需要数据库。 Also there is a few pages which don't need database, but because all pages pass from index.php then that connection executes.还有一些页面不需要数据库,但是因为所有页面都是从index.php传递的,所以该连接会执行。 I mean for all pages (even those ones which doesn't need database) there is a database connection.我的意思是所有页面(甚至那些不需要数据库的页面)都有一个数据库连接。

Is that a bad thing?那是一件坏事? Should I change all my structure?我应该改变我所有的结构吗? Again, the most of the pages need database, just a few of them doesn't.同样,大多数页面都需要数据库,只有少数页面不需要。 So is what I do fine?那我做的好吗?

You need to create a singleton class for the DB connection, and not just run the code.您需要为数据库连接创建一个单例类,而不仅仅是运行代码。

class DB {
    private static $instance;
    private $_dbh_conn = null;

    public static function getInstance() {
        if (null === static::$instance) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    protected function __construct() { 
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "dbname";
        $this->_dbh_conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $this->_dbh_conn->exec("set names utf8");
        $this->_dbh_conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        $this->_dbh_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

    public function &dbh_conn() {
        return $this->_dbh_conn;
    }

    private function __clone() { }
    private function __wakeup() { }
}

And when you include this file, you need to get the connection like this:当你包含这个文件时,你需要像这样获得连接:

$dbh_conn = DB::getInstance()->dbh_conn(); 

Now you have the connection to the database in $dbh_conn and you can use it just as you did up until now.现在您已经在$dbh_conn建立了到数据库的连接,您可以像之前一样使用它。 The only difference is that now you can include this file, but it won't connect to the DB unless you use the Singleton class DB and specifically requesting the DB connection (as I did in the above example).唯一的区别是现在您可以包含此文件,但除非您使用 Singleton 类DB并专门请求 DB 连接(如我在上面的示例中所做的那样),否则它不会连接到数据库。 Additional benefit is that you're getting the same DB connection throughout the runtime of the script because you're using a design pattern of a singleton class to get the connection.额外的好处是您在脚本的整个运行时获得相同的数据库连接,因为您使用单例类的设计模式来获得连接。

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

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