简体   繁体   中英

PDO with extended PDOStatement cannot disconnect the connection when set NULL

Tested in PHP 5.5.22 and 5.5.25

When using PDO that has extended PDOStatement, MySQL keep connection until when PHP script are finished.

use PDO;

$dbinfoCode = array(
    'userid' => 'userid',
    'password' => 'password',
    'engine' => 'mysql',
    'host' => '192.168.100.2',
    'database' => 'test',
);


for ($i = 0; $i < 10000; $i++) {

    $dsn = sprintf("%s:host=%s;dbname=%s", $dbinfo['engine'], $dbinfo['host'], $dbinfo['database']);

    $pdo = new PDO($dsn, $dbinfo['userid'], $dbinfo['password'], $options);
    $pdo->setAttribute (PDO::ATTR_STATEMENT_CLASS, array ('PDOStatement2', array($pdo)));
    $pdo = null;

}

class PDOStatement2 extends PDOStatement {
}

I can see increasingly stacked "Sleep" processes on MySQL query. Finally, MySQL throw error "Too many connections".

SHOW PROCESSLIST;

If there is no setAttribute about PDO::ATTR_STATEMENT_CLASS , The MySQL connection is disconnected in working order.

    $pdo = new PDO($dsn, $dbinfo['userid'], $dbinfo['password'], $options);
    //$pdo->setAttribute (PDO::ATTR_STATEMENT_CLASS, array ('PDOStatement2', array($pdo)));
    $pdo = null;

I have no idea about it wheather is this a bug or has another solutions.

Finally, I found the solution.

$pdo object on following statement will be duplicated

$pdo->setAttribute (PDO::ATTR_STATEMENT_CLASS, array ('PDOStatement2', array($pdo)));

Use &$pdo instead of $pdo .

$pdo->setAttribute (PDO::ATTR_STATEMENT_CLASS, array ('PDOStatement2', array(&$pdo)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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