postgres 中的 Php PDO 连接

标签 php postgresql pdo connection

我有一个 php 脚本,它被 ajax 以 4 秒的间隔一次又一次地调用。

try {
    $conn_p = new PDO("pgsql:host=$db_host;dbname=$db_dbname", $db_user, $db_password);
} catch(PDOException $e) {  
    //$e->getMessage();
}

function abc($id)
{
    global $conn_p;

    $st = "select * from table where id=:id";
    $sqlst=$conn_p->prepare($st);
    $bindParamArray=array("id"=>$id);
    $sqlst->execute($bindParamArray);   
    $row=$sqlst->fetch();   
    return $row;
}

function xyz($no)
{
    global $conn_p; 
    $st= "select * from table2 where no=:no and display='Y'";
    $sqlst=$conn_p->prepare($st);
    $bindParamArray=array(':no' => $no);
    $sqlst->execute($bindParamArray);   
    $row=$sqlst->fetch();   
    return $row;
}

function abc($id)
{
    global $conn_p;

    $st = "select * from table where id=:id";
    $sqlst=$conn_p->prepare($st);
    $bindParamArray=array("id"=>$id);
    $sqlst->execute($bindParamArray);   
    $row=$sqlst->fetch();   
    return $row;
}

function getData()
{
    global $conn_p; 
    $st= "select * from table2";
    $sqlst=$conn_p->prepare($st);
    $sqlst->execute();  
    $row=$sqlst->fetchAll();    
    return $row;
}
........same other functions

$data = getData();

foreach ($data as $dd) {

    $abc[] = abc($dd['id']);
    $xyz[] = xyz($dd['no']);
    //some other manipulations......
}

echo json_encode(array('data1'=>$abc,'data2'=>$xyz));

运行sql命令时

select * from pg_stat_activity

它显示了多个连接。(我的服务器管理员告诉我的)

现在我的问题是:

  • 我需要关闭连接吗?
  • 如果是,那么什么时候关闭它?
  • 如果发生错误怎么办?

最佳答案

一些建议:

  1. 不,您不需要关闭连接,除非您的脚本运行了很长时间并且您在它进行耗时操作时没有使用它。脚本完成后,连接将自动关闭。
  2. 您可能不应该每隔 x 秒从数据库中获取所有行。只有新的或更改的行应该更有效。您真的需要页面中的所有行吗?
  3. 您不应使用短时间间隔运行 ajax 调用。而是执行 ajax 调用并在当前 ajax 调用完成时为下一次调用设置超时。这样请求就永远不会重叠。

关于postgres 中的 Php PDO 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48080004/

相关文章:

php - 同域多表单认证

sql - 使用 Postgresql 计算数学级数

php - PDO 查询未执行

python - 我如何在python中获取Postgresql中的数据库列表

php - unlink 似乎不适用于 foreach 循环

php - 在 mysql 中使用 IF 语句选择更新

php - 获取根节点的XML命名空间

php - 将数组数据插入 MYSQL/PHP

php - 如何在 Laravel 中的连接查询中获取计数

postgresql - 如何向父表和子表插入数据