Languages such as node.js can implement asynchronous database query functions. There is no need to wait for the database to return results after executing the SQL statement. Continue to execute other codes. When the database returns the result, the data is processed, such as rendering the page and sending the HTML page to the client. In this way, the application does not need to block and wait at all. This method operates very efficiently.
Is it possible to implement similar asynchronous non-blocking MySQL queries in PHP? Use github to search and find a project that seems to do this function, https://github.com/kaja47/async-mysql. The code is based on React.PHP. But it's not really asynchronous SQL. The principle of implementation is to set a timer and poll every 0.02 seconds. Although it can be used, it is a waste of CPU resources. Not really asynchronous MYSQL.
Now Swoole1.6.2 provides 2 new functions, swoole_event_add and swoole_get_mysqli_sock, which can be used to achieve true PHP asynchronous MySQL. Let’s talk about the specific implementation.
Code:
$db = new mysqli;
$db->connect('127.0.0.1', 'root', 'root', 'test');
$db->query("show ", MYSQLI_ASYNC);
swoole_event_add(swoole_get_mysqli_sock($db), function($db_sock) {
global $db;
$res = $db->reap_async_query();
var_dump($res->fetch_all(MYSQLI_ ASSOC ));
swoole_event_exit();
});
First connect to mysql. After the connection is successful, execute the SQL statement and specify MYSQLI_ASYNC in the second parameter. Indicates that this query is asynchronous. The query function will return immediately, and mysqli_result is not obtained at this time.
Then call the swoole_get_mysqli_sock function to get the socket of the mysql connection, and call swoole_event_add to add it to the swoole's epoll event loop. When the database returns the result, the function we just formulated will be called back.
At this time, call mysqli_reap_async_query to get the result, and call the fetch_all function to get the data.
This process is completely asynchronous and non-blocking, and there is no code that wastes CPU. This code can also be used in server-side programs. The specific code implementation will be written in a detailed article later.