Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

php - PDO Global Instance New PDO , its possible?

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.

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);    
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...