Bibear
Bibear

Reputation: 69

Use of MySQL persistent connection in ZF2

On ZF2 I need to use a persistent MySQL connection and reconnect and the MySQL is gone away. But I can not figure out where I should activate the MYSQL_OPT_RECONNECT parameter.

My db adapters are definied as follow:

    'db' => array(
        'driver'         => 'Pdo',
        'dsn'            => 'mysql:dbname=DB_NAME;host=HOST',
        'driver_options' => array(
            PDO::MYSQL_ATTR_INIT_COMMAND        => 'SET NAMES \'UTF8\'',
        ),
        'username' => 'LOGIN',
        'password' => 'PWD',
    ),

I have tried things like :

'db' => array(
    'driver'         => 'Pdo',
    'dsn'            => 'mysql:dbname=DB_NAME;host=HOST',
    'driver_options' => array(
        PDO::MYSQL_ATTR_INIT_COMMAND        => 'SET NAMES \'UTF8\'',
        'AUTO_RECONNECT_ON_UNSERIALIZE'  => 1,
    ),
    'options'       => array(
        'AUTO_RECONNECT_ON_UNSERIALIZE'  => 1,
    ),
    'username' => 'LOGIN',
    'password' => 'PWD',
),

and nothing works.

How to make this mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconnect); happen somewhere ?

Upvotes: 0

Views: 1078

Answers (1)

Bibear
Bibear

Reputation: 69

Ok, the answer is :

'db' => array(
    'driver'         => 'Pdo',
    'dsn'            => 'mysql:dbname=DB_NAME;host=HOST',
    'driver_options' => array(
        PDO::MYSQL_ATTR_INIT_COMMAND        => 'SET NAMES \'UTF8\'',
    ),
    'options'       => array(
        PDO::ATTR_PERSISTENT => true',
    ),
    'username' => 'LOGIN',
    'password' => 'PWD',
),

But the use of persistant connection might not be a good fit for every one so you can also catch any "Mysql Server Gone Away Error" and proceed to a reconnect via :

 $this->tableGateway->getAdapter()->getDriver()->getConnection()->disconnect();
 $this->tableGateway->getAdapter()->getDriver()->registerConnection($this->getAdapter()->getDriver()->getConnection()->connect());
 if($this->tableGateway->getAdapter()->getDriver()->getConnection()->isConnected()) {
        return true;
 }

Upvotes: 1

Related Questions