Php postgres 中的 PDO 连接

Php PDO connection in postgres

我有一个 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

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

现在我的问题是:

这是我在 class for postgresql 中使用的。
与 mysql.

相同
$this->dsn = $this->driver . ':host=' . $this->host . ';port=' . $this->port . ';dbname=' . $this->name;

一些建议:

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