ukits
ukits

Reputation: 67

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.

Upvotes: 2

Views: 381

Answers (1)

ukits
ukits

Reputation: 67

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

Upvotes: 2

Related Questions