PHP 命令不同步错误

标签 php mysql mysqli

我在 PHP/MySQLi 中使用两个准备好的语句从 mysql 数据库中检索数据。但是,当我运行语句时,出现“命令不同步,您现在无法运行命令”错误。

这是我的代码:

    $stmt = $mysqli->prepare("SELECT id, username, password, firstname, lastname, salt FROM members WHERE email = ? LIMIT 1";
    $stmt->bind_param('s', $loweredEmail);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($user_id, $username, $db_password, $firstname, $lastname, $salt);
    $stmt->fetch();

    $stmt->free_result();
    $stmt->close();

    while($mysqli->more_results()){
        $mysqli->next_result();
    }

    $stmt1 = $mysqli->prepare("SELECT privileges FROM delegations WHERE id = ? LIMIT 1");
    //This is where the error is generated
    $stmt1->bind_param('s', $user_id);
    $stmt1->execute();
    $stmt1->store_result();
    $stmt1->bind_result($privileges);
    $stmt1->fetch();

我尝试过的:

  • 将准备好的语句移动到两个单独的对象中。
  • 使用代码:

    while($mysqli->more_results()){
        $mysqli->next_result();
    }
    //To make sure that no stray result data is left in buffer between the first
    //and second statements
    
  • 使用 free_result() 和 mysqli_stmt->close()

PS:“Out of Sync”错误来自第二条语句的“$stmt1->error”

最佳答案

在 mysqli::query 中,如果你使用 MYSQLI_USE_RESULT,所有后续调用都会返回错误 命令不同步,除非你调用 mysqli_free_result()

调用多个存储过程时,您可能会遇到以下错误:“命令不同步;您现在无法运行此命令”。 即使在调用之间对结果对象使用 close() 函数时,也会发生这种情况。 要解决此问题,请记住在每次存储过程调用后对 mysqli 对象调用 next_result() 函数。请参见下面的示例:

<?php
// New Connection
$db = new mysqli('localhost','user','pass','database');

// Check for errors
if(mysqli_connect_errno()){
 echo mysqli_connect_error();
}

// 1st Query
$result = $db->query("call getUsers()");
if($result){
     // Cycle through results
    while ($row = $result->fetch_object()){
        $user_arr[] = $row;
    }
    // Free result set
    $result->close();
    $db->next_result();
}

// 2nd Query
$result = $db->query("call getGroups()");
if($result){
     // Cycle through results
    while ($row = $result->fetch_object()){
        $group_arr[] = $row;
    }
     // Free result set
     $result->close();
     $db->next_result();
}
else echo($db->error);

// Close connection
$db->close();
?>

我希望这会有所帮助

关于PHP 命令不同步错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14554517/

相关文章:

php - 将我的站点从 XAMPP 上传到 Apache 公共(public)主机

php - jEditable 有问题

javascript - Discord 机器人开发的 SQL 语法问题 (mySQL 8.0)

php - MySQL 查询在 PHPMyAdmin 中工作但在 PHP 中不工作

php - 将文件内容转换为 JavaScript 数组

mysql - 如果mysql中已经存在函数,如何删除它

PHP:将多个数组插入mysql表

php - 在 PHP 中循环遍历 SQL 结果 - 没有得到整个数组

javascript - 将表单数据发送到 2 个地方

php - 当我使用 json_encode 时,为什么 PHP 对我的数字进行四舍五入?