2024 年 PHP 日本研討會

pg_get_result

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_get_result 取得非同步查詢結果

說明

pg_get_result(PgSql\Connection $connection): PgSql\Result|false

pg_get_result() 會從由 pg_send_query()pg_send_query_params()pg_send_execute() 執行的非同步查詢中取得一個 PgSql\Result 實例。

pg_send_query() 和其他非同步查詢函式可以向 PostgreSQL 伺服器發送多個查詢,而 pg_get_result() 則用於逐一取得每個查詢的結果。

參數

connection

一個 PgSql\Connection 實例。

返回值

一個 PgSql\Result 實例,如果沒有更多結果可用,則返回 false

更新日誌

版本 說明
8.1.0 現在返回一個 PgSql\Result 實例;以前返回的是一個 資源
8.1.0 connection 參數現在需要一個 PgSql\Connection 實例;以前需要的是一個 資源

範例

範例 #1 pg_get_result() 範例

<?php
$dbconn
= pg_connect("dbname=publisher") or die("無法連線");

if (!
pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
}

$res1 = pg_get_result($dbconn);
echo
"第一次呼叫 pg_get_result(): $res1\n";
$rows1 = pg_num_rows($res1);
echo
"$res1$rows1 筆記錄\n\n";

$res2 = pg_get_result($dbconn);
echo
"第二次呼叫 pg_get_result(): $res2\n";
$rows2 = pg_num_rows($res2);
echo
"$res2$rows2 筆記錄\n";
?>

以上範例將輸出

First call to pg_get_result(): Resource id #3
Resource id #3 has 3 records

Second call to pg_get_result(): Resource id #4
Resource id #4 has 1 records

參見

新增筆記

使用者貢獻的筆記 4 則筆記

william at 25thandClement dot com
19 年前
沒有辦法輪詢/等待通知的到來。您只能進入忙碌迴圈或休眠。兩種選擇都很糟糕。如果 PHP 能提供對 PQsocket 的存取權,這樣就可以在 socket 連線上使用 select(),那就太好了。這是從 C 或 Perl 完成的方式。
Ondej Bouda
9 年前
在僅發送單個查詢後呼叫 pg_get_result() 之後,連線似乎不會忙碌。然而,正確的方法是在迴圈中額外呼叫 pg_get_result(),直到它返回 false [1]。

<?php
$conn
= pg_connect('...', PGSQL_CONNECT_FORCE_NEW);
for (
$i = 0; $i < 10000; $i++) {
$query = '錯誤的查詢';
if (
pg_connection_busy($conn)) {
fprintf(STDERR, "連線忙碌\n");
exit(
1);
}
pg_send_query($conn, $query);
$res = pg_get_result($conn);
if (
$res === false) {
fprintf(STDERR, "預期會有結果\n");
exit(
1);
}

/* 以下內容對於正確的查詢來說似乎並非必要,但對於錯誤的查詢至關重要。
將迴圈註釋掉會導致此腳本因「連線忙碌」錯誤而失敗。 */
while (pg_get_result($conn));

// 結果處理...
}
?>

詳情請參閱 https://postgresql.dev.org.tw/message-id/flat/gtitqq$26l3$1@news.hub.org#gtitqq$26l3$1@news.hub.orghttps://bugs.php.net/bug.php?id=52750

[1] 或者,更好的方法是使用 PHP 5.6 以來的非同步連線。
gullevek at gullevek dot org
11 年前
要使用非同步查詢獲得簡單的等待輸出,您可以使用 pg_connection_busy 指令

<?php
$dbh
= pg_connect("host=XXX user=XXX password=XXX dbname=XXX");
if (!
$dbh)
{
print
"連線失敗";
exit;
}

$query = "SELECT pg_sleep(10)";
if (!
pg_connection_busy($dbh))
{
$sent = pg_send_query($dbh, $query);
print
"已送出查詢,等待中:";
while (
pg_connection_busy($dbh)
{
print
".";
flush();
}
$res = pg_get_result($dbh);
print
"<br>"; // 或 \n
print "結果為: $res";
}

pg_close($dbh);
?>
Marko Tiikkaja
16 年前
william at 25thandClement dot com 表示:「沒有辦法輪詢/等待通知的到來。..」
有的,如果查詢正在進行中,pg_get_result() 會阻塞並在查詢完成時返回結果。
To Top