mysqli_multi_query - 命令不同步;你现在不能 运行 这个命令

mysqli_multi_query - Commands out of sync; you can't run this command now

我有几个查询字符串,我想使用 "mysqli_multi_query" 立即执行。这行得通。

当我再次插入查询以使用 "mysqli_query" 检查连接表中的每个项目时,它不会 return 任何结果 也不会 来自 PHP。当我 运行 在 phpmyadmin 中手动查询字符串时,一切正常。

这是我的代码:

<?php

$connect   = mysqli_connect('localhost','root','','database');
$strquery  = "";
$strquery .= "1st Query";
$strquyer .= "2nd Query";
if($multi = mysqli_multi_query($connect,$strquery)){   // function mysqli_multi_query is working
     // From here it doesn't give any response
     $qryarray = mysqli_query($connect, 
                              "SELECT purchase_detail_$_SESSION[period].item_code,
                                      purchase_detail_$_SESSION[period].location_code
                               FROM   purchase_detail_$_SESSION[period] 
                               WHERE  purchase_detail_$_SESSION[period].purchase_num = '$_POST[purchase_num]' 
                               UNION
                               SELECT purchase_detail_temp.item_code,
                                      purchase_detail_temp.location_code
                               FROM   purchase_detail_temp 
                               WHERE  purchase_detail_temp.purchase_num = '$_POST[purchase_num]' AND purchase_detail_temp.username = '$_SESSION[username]'");
     while($array = mysqli_fetch_array($qryarray)){
          "Some code to process several item code in table purchase_detail_$_SESSION[period]"
     }
}

我的代码有问题吗?

我刚刚在 the PHP manual 中找到了答案:

WATCH OUT: if you mix $mysqli->multi_query and $mysqli->query, the latter(s) won't be executed!

BAD CODE:

$mysqli->multi_query(" Many SQL queries ; "); // OK
$mysqli->query(" SQL statement #1 ; ") // not executed!
$mysqli->query(" SQL statement #2 ; ") // not executed!
$mysqli->query(" SQL statement #3 ; ") // not executed!
$mysqli->query(" SQL statement #4 ; ") // not executed!

The only way to do this correctly is:

WORKING CODE:

$mysqli->multi_query(" Many SQL queries ; "); // OK
while ($mysqli->next_result()) {;} // flush multi_queries
$mysqli->query(" SQL statement #1 ; ") // now executed!
$mysqli->query(" SQL statement #2 ; ") // now executed!
$mysqli->query(" SQL statement #3 ; ") // now executed!
$mysqli->query(" SQL statement #4 ; ") // now executed!

我只是在 mysqli_multi_query() 之后插入此代码:

while(mysqli_next_result($connect)){;}

作为爱迪生回答的补充:

while(mysqli_next_result($connect)){;}

我会推荐这段代码。这避免了异常。

while(mysqli_more_results($con))
{
   mysqli_next_result($con);
}