php 8.6可以先用pg_send_query_params提交参数查询,再通过pg_consume_input、pg_connection_busy和套接字可读事件等待结果。提交成功只代表命令已发送,不代表sql执行成功;还必须逐个取得结果并检查状态。

PHP手册中的pg_send_query_params
等待单个受控查询并设置应用预算
<?php $dsn=getenv('PG_DSN');
if (!is_string($dsn) || $dsn==='') throw new RuntimeException('缺少连接配置');
$conn=pg_connect($dsn,PGSQL_CONNECT_FORCE_NEW);
if ($conn===false) throw new RuntimeException('数据库连接失败');
try {
$sent=pg_send_query_params($conn,
'SELECT id,name FROM products WHERE id=$1::int',[12]);
if (!$sent) throw new RuntimeException('查询未成功发送');
$socket=pg_socket($conn);
if ($socket===false) throw new RuntimeException('无法取得连接套接字');
$deadline=hrtime(true)+2_000_000_000;
while (true) {
if (!pg_consume_input($conn)) throw new RuntimeException('连接读取失败');
if (!pg_connection_busy($conn)) break;
if (hrtime(true)>$deadline) {
pg_cancel_query($conn);
throw new RuntimeException('等待预算已用尽');
}
$read=[$socket]; $write=[]; $except=[];
if (stream_select($read,$write,$except,0,100000)===false) {
throw new RuntimeException('等待套接字失败');
}
}
while (($result=pg_get_result($conn))!==false) {
try {
if (pg_result_status($result)!==PGSQL_TUPLES_OK) {
throw new RuntimeException('SQL执行未成功');
}
echo json_encode(pg_fetch_all($result),JSON_THROW_ON_ERROR),PHP_EOL;
} finally { pg_free_result($result); }
}
} finally { pg_close($conn); }

PHP手册中的pg_consume_input
连接建立和服务端时限另行配置
示例使用64位PHP,查询只返回有限字段与一条记录;PG_DSN应包含受控连接参数、connect_timeout和适当的服务端statement_timeout。建立连接并不是异步的,发送大查询也不承诺完全无等待。
取消不等于精确硬截止
应用预算用于发起取消并停止采用结果,取消请求本身也可能等待网络,不保证恰好两秒结束。pg_consume_input返回true不代表一定收到了数据。出错或取消后示例关闭专用连接,不把仍有未读状态的连接直接复用;成功时应把所有结果取尽。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










