The problem
I've got a large query which I want to be terminated as soon as the user aborts. I've searched and came across the following questions:
- Kill MySQL query on user abort
- KILL MySQL queries using PHP if user close the browser or navigate from one page to other page
- Killing a MySQL query during execution with PHP and AJAX
From these questions I substracted the usefull parts which resulted in the code below.
Code
// Connection to query on
$query_con = mysqli_connect($host, $user, $password, $name);
// Connection to kill on
$kill_con = mysqli_connect($host, $user, $password, $name);
$slow_query = "...";
// Start the query
$query_con->query($slow_query, MYSQLI_ASYNC);
// Get the PID
$thread_id = $query_con->thread_id;
// Ignore user abort so we can kill the query
ignore_user_abort(true);
do {
// Poll MySQL
$links = $errors = $reject = array($mysqli->mysqli);
$poll = mysqli_poll($links, $errors, $reject, 0, 500000);
// Check if the connection is aborted and the query was killed
if (connection_aborted() && mysqli_kill($kill_con, $thread_id)) {
die();
}
} while (!$poll);
// Not aborted, so do stuff with the result
$result = $link->reap_async_query();
if (is_object($result)) {
// Select
while ($row = $result->fetch_object()) {
$articles[] = $row;
}
}
echo count($articles);
Errors
The above code throws me the following errors:
- Notice: Use of undefined constant MYSQLI_ASYNC - assumed 'MYSQLI_ASYNC'
- Warning: mysqli::query() expects parameter 2 to be long, string given
- Notice: Undefined variable: mysqli
- Notice: Trying to get property of non-object
- Fatal error: Call to undefined function mysqli_poll()
Question
I am really stuck here and do not know how to go forward from this point.