Regarding the failure to process them all now, then retrieve the results later, I found that all queries would return successfully if I added a further condition to your while loop in the "stack_query()" method.
By adding:
&& (pg_transaction_status($conn) === PGSQL_TRANSACTION_IDLE ) )
Every query executed with no errors.
<?php
$conn = pg_connect("dbname=dbname host=localhost user=psql ");
if ($conn === FALSE)
exit("Can't connect to db");
$q = array();
foreach (range(0, 50) as $i)
stack_query($q, $conn, "SELECT 'query $i' AS str;");
while (true)
{
$left = stack_query($q, $conn);
echo "$left left... ";
$result = pg_get_result($conn);
if ($left == 0 && $result === FALSE)
break;
$row = pg_fetch_assoc($result);
echo "got $row[str]\n";
}
function stack_query(&$queries, $conn, $sql = FALSE)
{
if ($sql !== FALSE)
$queries[] = $sql;
while (count($queries) && !pg_connection_busy($conn) && (pg_transaction_status($conn) === PGSQL_TRANSACTION_IDLE ) )
pg_send_query($conn, array_shift($queries));
return count($queries) + (pg_connection_busy($conn) ? 1 : 0);
}
?>