【发布时间】:2018-01-03 15:04:38
【问题描述】:
我有一个 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
它显示了多个连接。(我的服务器管理员告诉我)
现在我的问题是:
- 我需要关闭连接吗?
- 如果是,那么什么时候关闭呢?
- 如果出现错误怎么办?
【问题讨论】:
-
根据设置的具体情况,您可能需要考虑使用持久连接。 php.net/manual/en/pdo.connections.php
-
您应该考虑使用以下命令关闭 PDO:$conn_p = null;
-
好的,何时使用 $conn_p = null;我的意思是在我上面的脚本中在哪里写它,在脚本的末尾还是?
标签: php postgresql pdo connection