【问题标题】:Why I am getting the Error "Commands out of sync; you can't run this command now"为什么我收到错误“命令不同步;您现在无法运行此命令”
【发布时间】:2013-05-02 13:43:17
【问题描述】:

标题中提到的错误的文档说

如果您得到命令不同步;您现在无法运行此命令 您的客户端代码,您以错误的顺序调用客户端函数。

这可能发生,例如,如果您使用 mysql_use_result() 并且 在调用 mysql_free_result() 之前尝试执行新查询。 如果您尝试执行两个返回数据的查询,也会发生这种情况 中间不调用 mysql_use_result() 或 mysql_store_result()。

从这里:http://dev.mysql.com/doc/refman/5.0/en/commands-out-of-sync.html

但是在第一个查询中,我没有从 mysql 数据库中获取任何数据,我只是在插入。在第二个查询中,我从数据库中获取数据。

这是我的代码

$connection = mysqli_connect("localhost","username","password","tbl_msgs");
if(mysqli_connect_errno($connection))
{
    die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$query = "INSERT INTO users (total_comments, total_views) 
          VALUES ({$total_comments}, {$total_views});";

$query .= "INSERT INTO msgs (notifications) VALUES ({$notifications})";

mysqli_multi_query($connection,$query);

到这一步为止,一切都很好。但是当我执行以下查询时它给出了错误

$select_query = "SELECT * FROM msgs WHERE msg_id = {$msg_id}";

$result_set = mysqli_query($connection,$select_query);

if(!$result_set) {
    die(mysqli_error($connection)); 
}

这里给出了错误Commands out of sync; you can't run this command now。我无法理解这种情况

注意:查询中有任何问题,我已经直接对 PHPMyAdmin 执行了相同的查询,它工作正常。

【问题讨论】:

    标签: php mysqli mysqli-multi-query


    【解决方案1】:

    查询中有待处理的结果集:

    mysqli_multi_query($connection,$query);

    您需要先使用/存储结果,然后才能继续下一个查询: 由于您看起来并不真正关心第一个结果集,因此请在多查询之后执行此操作..

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

    另一种选择是关闭连接并重新启动它..

    mysqli_close($connection);
    $connection = mysqli_connect("localhost","username","password","tbl_msgs");
    

    这一切都取决于您的要求。

    【讨论】:

    • 为什么我需要用 mysqli 而不是 mysql?
    • mysql_* 函数自 PHP 5.5.0 版起已弃用。
    猜你喜欢
    • 2015-12-21
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 2012-07-19
    • 1970-01-01
    • 2013-12-27
    相关资源
    最近更新 更多