PDO 全局实例 新的 PDO ,它可能吗?

2021-12-26 00:00:00 function php pdo

我使用 PHP PDO 连接到我的数据库并运行一些查询,然后在某些表单上使用查询返回.

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 values ​​coming from the query.

我创建了两个函数来连接数据库和数据,但我想知道我是否可以创建一个全局变量,因为我使用的是New PDO".

I created two functions to connect to the database and data, but I wanted to know if I can create a global variable because I am using the "New PDO" .

/** Conecta com as impressas **/
function impressoras()
{       
    $PDO2 = new PDO('mysql:host=localhost;dbname=ti','root','xxx');
    $PDO2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    global $stmt;
    $stmt = $PDO2->prepare("SELECT * FROM league");
    $stmt->execute();
    $result = $stmt->fetchAll();
    return $result; 
    echo json_encode($user_arr);    
}
function carrefour()
{
    $PDO3 = new 
    PDO('mysql:host=localhost;dbname=ti','root','xxx');
    $PDO3->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    global $stmt;
    $stmt = $PDO3->prepare("SELECT * FROM lol");
    $stmt->execute();
    $result = $stmt->fetchAll();
    return $result;     
    echo json_encode($user_arr);    
}

推荐答案

您可以以简单的旧程序风格非常简单地共享"同一个数据库连接对象 (PDO) :-) 这是一个简单的例子:

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;
}

用法

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

如果您更喜欢更专业的解决方案,请查看 PHP-DI 并使用依赖注入.

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

相关文章