PHP的MySQLi多查询异步? [英] php mysqli multi query asynchronous?

查看:57
本文介绍了PHP的MySQLi多查询异步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$databases = array();
$path = '/Path/To/Directory';
$main_link = mysqli_connect('localhost', 'USERNAME', 'PASSWORD');
$files = scandir($path);
$ignore_files = array();

foreach($files as $file)
{
    if (!in_array($file, $ignore_files))
    {
        $database = substr($file, 0, strpos($file,'.'));
        $databases[] = $database;
        mysqli_query($main_link, "DROP DATABASE IF EXISTS $database") or die ("$database 1" . mysqli_error($main_link));
        mysqli_query($main_link, "CREATE DATABASE $database") or die ("$database 2" .mysqli_error($main_link));
        $db_link = mysqli_connect('localhost', 'USERNAME', 'PASSWORD', $database);
        //In here a whole database dump with scheam + data is executed. 
        mysqli_multi_query($db_link, file_get_contents($path.'/'.$file)) or die ("$database 4" .mysqli_error($db_link));        
    }   
}

运行此脚本时,它很快完成了操作(返回浏览器),但是在浏览器说完成之后,它仍在运行查询.为什么会这样?

When running this script it was done very quickly (returned to browser), but it was still running queries after the browser said it was done. Why is this?

推荐答案

mysqli_query 支持异步查询.请参阅mysqli_query上的更改日志. mysqli_multi_query 在手册页上没有专门提到异步. mysqli_multi_query唯一要做的就是告诉MySQL执行大量查询.等待结果由PHP决定.

mysqli_query supports async queries. See changelog on mysqli_query. mysqli_multi_query does not mention async on the manual page specifically. Only thing mysqli_multi_query does is tell MySQL to execute a bulk set of queries. It's up to PHP to wait for the results.

按照您的代码立场,您将向MySQL发送大量SQL语句,而不等待任何结果.第一条语句失败时,只有mysqli_multi_query会出现die的时间.因此,该函数在第一条语句之后立即返回true,然后继续进行下一行.这就是为什么在PHP完成后才执行查询的原因. MySQL仍在工作. PHP已经发展.

As your code stands, your sending a bulk set of SQL statements to MySQL and not waiting for any results. Only time your mysqli_multi_query will ever die is when the first statement fails. So, that function returns true immediately after the first statement and moves on to the next line. That's why the queries are executing after the PHP is finished. MySQL is still working. PHP has moved on.

最好先遍历每个语句的结果,然后再继续执行代码.如果查询在批处理中的任何地方失败,则以下内容将die.

It's best that you loop through the results of each statement before moving on with your code. The following will die if a query fails anywhere in your batch.

mysqli_multi_query($db_link, file_get_contents($path.'/'.$file)) or die ("$database 4" .mysqli_error($db_link)); 

do {
    if($result = mysqli_store_result($db_link)){
        mysqli_free_result($result);
    }
} while(mysqli_next_result($db_link));

if(mysqli_error($db_link)) {
    die(mysqli_error($db_link));
}

这篇关于PHP的MySQLi多查询异步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆