mysqli提供了异步执行sql的功能,类似于select轮询机制。先提交SQL到预发布,再去轮询查询是否ok。query的时候加上MYSQLI_ASYNC选项,query就直接提交到mysql,但是本身不等待执行结果。mysqli不亏是加强版的mysql扩展,可惜不是pdo
<?php /** * 执行SQL * @param $sql * @return mysqli */ function query($sql) { // 1.创建连接 $servername = "localhost"; $username = "root"; $password = "root"; $database = "test"; $conn = new mysqli($servername, $username, $password, $database); if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 2.异步提交SQL $conn->query($sql, MYSQLI_ASYNC); // 3.返回SQL连接 return $conn; } // 1.保存全部的Conn变量 $all_conn = []; // 2.循环提交异步SQL $i = 4; while ($i--) { $sql = "select scenes_name_cn from erp_allocation_scenes where id = $i"; $all_conn [] = query($sql, MYSQLI_ASYNC); } // 3.循环等待全部的结果 $allResult = []; do { $links = $errors = $reject = $all_conn; if (!mysqli_poll($links, $errors, $reject, 1)) { continue; } foreach ($all_conn as $conn) { if ($result = $conn->reap_async_query()) { $allResult[] = $result->fetch_row(); if (is_object($result)) { $result->free(); } } else { throw new mysqli_sql_exception(sprintf("MySQLi Error: %s", mysqli_error($conn))); } } } while (count($allResult) == 5); // 4.输出查询结果 print_r($allResult);