简体   繁体   English

php mysqli 多查询异步?

[英]php mysqli multi query asynchronous?

$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 supports async queries. mysqli_query支持异步查询。 See changelog on mysqli_query .请参阅mysqli_query上的更改日志。 mysqli_multi_query does not mention async on the manual page specifically. mysqli_multi_query在手册页上没有特别提到异步。 Only thing mysqli_multi_query does is tell MySQL to execute a bulk set of queries. mysqli_multi_query唯一要做的就是告诉 MySQL 执行一组批量查询。 It's up to PHP to wait for the results.等待结果取决于 PHP。

As your code stands, your sending a bulk set of SQL statements to MySQL and not waiting for any results.就您的代码而言,您向 MySQL 发送大量 SQL 语句而不等待任何结果。 Only time your mysqli_multi_query will ever die is when the first statement fails.只有当第一个语句失败时,您的mysqli_multi_query才会die So, that function returns true immediately after the first statement and moves on to the next line.因此,function 在第一条语句之后立即返回 true 并移至下一行。 That's why the queries are executing after the PHP is finished.这就是在 PHP 完成后执行查询的原因。 MySQL is still working. MySQL 仍在工作。 PHP has moved on. PHP 继续前进。

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.如果您的批处理中的任何地方查询失败,则以下内容将die

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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM