Macbernie Macbernie - 3 months ago 12
PHP Question

Do not reconnect the database for controler call

My controler call a method who is requested the database and return the result.

$connect = $this->connectBDD();

$rq = "SELECT naf, libelle FROM mytable WHERE naf ILIKE '$txt%'";
$t = $connect->prepare($rq); $t->execute();
$t->setFetchMode(\PDO::FETCH_OBJ);

$tab = array();
while($top = $t->fetch()) {
$tab[] = array(
"text" => $top->naf . ": " . $top->libelle,
"value" => $top->naf
);
}

$t->closeCursor();

return $tab;


The problem comes from the first line $connect = $this->connectBDD(); who open the connexion. It takes times, ~ 1 seconde, and because this method is call very often (auto completion system), I need to memorize the connection to not reconnect at each call.

I try to memorize $connect in session

if( null === $this->app['session']->get('ac') ) {
$this->app['session']->set('ac', $this->connectBDD() );
}

$connect = $this->app['session']->get('ac');


$rq = "SELECT naf, libelle FROM mytable WHERE naf ILIKE '$txt%'";
$t = $connect->prepare($rq); $t->execute();
$t->setFetchMode(\PDO::FETCH_OBJ);

$tab = array();
while($top = $t->fetch()) {
$tab[] = array(
"text" => $top->naf . ": " . $top->libelle,
"value" => $top->naf
);
}

$t->closeCursor();

return $tab;


But it's worse, as if I have an infinite loop...

So, how can I call my method without reconnect the database at each call ?

Thanks for help

Answer

Try to make persistent connection in connectBDD

$dbh = new PDO('....', $user, $pass, array(
    PDO::ATTR_PERSISTENT => true
));

http://php.net/manual/en/pdo.connections.php

Comments