PHP’s mysqli::reap_async_query blocks

php
Published

June 30, 2013

Just a quick note about mysqli::reap_async_query since the official documentation is surprisingly lacking, and I’ve never had any luck getting user-contributed comments posted to the php pmanual.

The manual has this to say about mysqli::query(“…”, MYSQLI_ASYNC): “With MYSQLI_ASYNC (available with mysqlnd), it is possible to perform query asynchronously. mysqli_poll() is then used to get results from such queries.”

Does this mean that the only safe way to call reap_async_query is to first poll for connections with complete queries, and only call reap_async_query on connections that you know have results ready? No. Here’s a quick sample script to show what happens if you skip mysqli_poll() -

<?php
$dbhost = "localhost";
$dbuser = "someuser";
$dbpass = "somepass";
$dbschema = "db_name";

$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbschema);
$mysqli->query("SELECT SLEEP(5) AS sleep, 'query returned' AS result", MYSQLI_ASYNC);

echo 'Output while query is running...<br>';

$result = $mysqli->reap_async_query();
$resultArray = $result->fetch_assoc();

echo 'Got back "' . $resultArray["result"] . '" from query.';

outputs (after 5 seconds):

Output while query is running...<br>Got back "query returned" from query.

So, it appears that reap_async_query will block waiting for the query running on the mysqli instance to complete, if that query is not ready yet. So, in many cases, there is no need to use mysqli_poll() at all.