phpasynchronousmysqlimysqlnd

Best way to call and "forget about" an async mysqlnd INSERT query


Setup

I'm working with php and mysql in this situation.

Let's say I have my mysqli connection like this:

$link = new mysqli('localhost', 'root', 'password', 'A_Database');

I have installed mysqlnd to perform asynchronous mysql queries using the 'MYSQL_ASYNC' parameter:

$link->query("INSERT INTO `A_Table` VALUES('stuff!')", MYSQLI_ASYNC);

Goal

I just want to insert a record, and I don't need to retrieve it until the distant future so I'm not concerned about how long it takes for the asynchronous query to finish up, and I don't need to perform some final action when I know the query is complete. I do need to perform other unrelated mysql queries once I'm past the section of the code where the insert queries occur.

Problem

Performing a query like this will block other queries later in the script with out-of-sync errors. In order to deal with that, I had to add something like the following code after every async query:

$links = $errors = $reject = array($link);
if ($link->poll($links, $errors, $reject, 1)) {
    foreach ($links as $resultLink) {
        if ($result = $resultLink->reap_async_query()) {
            if (is_object($result)) {
                $result->free();
            }
        }
    }
}

This effectively stops the out-of-sync errors and my code works fine.
Two things still trouble me though:

  1. I don't want to have to bother with this, because I'm only performing insert queries and I don't care about having some response in my code when I know the inserts are complete.

  2. The polling code runs really really slowly on my server; far slower than performing a regular query and synchronously get the results back.

Recap

I want to run the insert query with two requirements; the query is non-blocking (asynchronous), and I can still perform other mysql queries later on. I just want to insert-query and 'forget about it', and just move on with my code.

Any suggestions as to what the best way to do this is?


Solution

  • If your goal is to insert a record and continue executing code without worrying about the result you can use INSERT DELAYED syntax without the need for the ASYNC flag:

    $link->query("INSERT DELAYED INTO `A_Table` VALUES('stuff!')" );
    

    It returns right away and you can continue executing new querys on the same connection. We use this on our logs system.