不要重新连接数据库以进行控制器调用

时间:2016-08-18 17:31:49

标签: php sql postgresql pdo silex

我的控制器调用请求数据库并返回结果的方法。

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

问题来自第一行$ connect = $ this-> connectBDD();谁打开了联系。这需要时间,约1次,并且由于这种方法经常被调用(自动完成系统),我需要记住连接,以便在每次调用时不重新连接。

我尝试在会话中记住$ connect

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;

但更糟糕的是,好像我有一个无限循环......

那么,如何在每次调用时不重新连接数据库的情况下调用我的方法?

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

尝试在connectBDD

中建立持久连接
$dbh = new PDO('....', $user, $pass, array(
    PDO::ATTR_PERSISTENT => true
));

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