php
  • mysql
  • mysqli
  • 2014-11-02 31 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; 
    } 
    

    當然,你或許應該在這個循環檢查錯誤

    相關問題