It might seem that after calling pg_get_result() upon sending just a single query, the connection will not be busy. The correct way is, though, to call extra pg_get_result() in a loop until it returns false [1].
<?php
$conn = pg_connect('...', PGSQL_CONNECT_FORCE_NEW);
for ($i = 0; $i < 10000; $i++) {
$query = 'erroneous query';
if (pg_connection_busy($conn)) {
fprintf(STDERR, "Connection is busy\n");
exit(1);
}
pg_send_query($conn, $query);
$res = pg_get_result($conn);
if ($res === false) {
fprintf(STDERR, "A result was expected\n");
exit(1);
}
/* The following does not seem necessary for good queries, but is vital for erroneous queries.
Commenting the loop out leads to this script fail with the "Connection is busy" error. */
while (pg_get_result($conn));
// result processing...
}
?>
See http://www.postgresql.org/message-id/flat/[email protected]#[email protected] and https://bugs.php.net/bug.php?id=52750 for detailed information.
[1] Or, even better, use an asynchronous connection since PHP 5.6.