php
  • mysql
  • mysqli
  • 2014-11-02 33 views 1 likes 
    1

    我一直在阅读有关Commands out of sync; you can't run this command now问题一段时间,并且看到您不能有任何未读的结果,这对我来说很有意义。但是,在以下情况下,我看不到我缺少哪些结果以免费。我从下面的PHP和SQL代码中省略了无关的内容。命令不同步,即使第一个SQL查询不包含结果

    # Set local variables 
    $sql = " 
        SET @STARTDATE = '2014-09-01'; 
        SET @RANK = 0; 
    "; 
    if (mysqli_multi_query($conn, $sql)) { 
        # Success: do nothing else 
    } else { 
        # Failure: output the error message 
        echo "Error: " . $sql . "<br>" . $conn->error; 
    } 
    
    # Fetch and store the results 
    $sql = " 
        SELECT * FROM MyTable 
    "; 
    $result = mysqli_query($conn, $sql); 
    if (!$result) { 
        echo "Error: " . $sql . "<br>" . mysqli_error($conn); 
    } 
    

    第二查询(在if (!$result)块)返回臭名昭著Commands out of sync错误。如果我注释掉第一部分,则第二个查询运行没有问题。如果我将第一个查询改为只有一个SET而不是两个,第二个查询运行没有问题。因此,我似乎必须清除第一部分中每条SQL语句的'成功标志'。它是否正确?如果是这样,该怎么办?

    编辑:事实上,似乎你必须冲刷所有结果之间。在第1部分和第2部分之间添加以下行解决了这个问题。

    while (mysqli_next_result($conn)) {;} // Flush multi_queries 
    

    我发现在PHP手册,用户评论此解决方案:http://nl3.php.net/manual/en/mysqli.multi-query.php

    回答

    1

    很简单,你的第一个查询

    SET @STARTDATE = '2014-09-01'; 
    SET @RANK = 0; 
    

    将产生2个的结果集,直到他们被处理,即使结果只是一个状态,你不能继续。

    所以,你需要做这样的事情: -

    if (mysqli_multi_query($conn, $sql)) { 
        do { 
         /* unload result set */ 
         if ($result = $mysqli->store_result()) { 
          // Check status 
          $result->free(); 
         } 
        } while ($mysqli->next_result()); 
    } else { 
        # Failure: output the error message 
        echo "Error: " . $sql . "<br>" . $conn->error; 
    } 
    

    当然,你或许应该在这个循环检查错误

    相关问题