PDO Global Instance New PDO , its possible?

前端 未结 2 1798
执笔经年
执笔经年 2020-12-12 08:36

I am using PHP PDO to connect to my database and run some querys to then use the query return on some forms.

That is, I have a select where it is populated by the va

2条回答
  •  执笔经年
    2020-12-12 08:56

    You could "share" the same database connection object (PDO) very simple in plain old procedural style :-) Here is a simple example:

    // config.php
    define('DB_DSN', 'mysql:host=127.0.0.1;dbname=test;charset=utf8');
    define('DB_USERNAME', 'root');
    define('DB_PASSWORD', '');
    
    // database.php
    function db()
    {
        static $db = null;
        if ($db === null) {
            $db = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD, array(
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_PERSISTENT => false,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8 COLLATE utf8_unicode_ci"
            ));
        }
        return $db;
    }
    

    Usage

    function test1()
    {       
        $pdo = db();
        $stmt = $pdo->prepare("SELECT * FROM league");
        $stmt->execute();
        $result = $stmt->fetchAll();
        return $result;     
    }
    

    If you prefer a more professional solution then take a look an PHP-DI and use dependency injection.

提交回复
热议问题