mysql:命令不同步;你现在不能 运行 这个命令 -> 当 php 函数中的查询是 运行 时

mysql: Commands out of sync; you can't run this command now -> when query is run in php function

有这个代码:

 $sql = "SELECT * FROM users WHERE user_login=?;";
        $stmt = mysqli_stmt_init($conn);

        if (!mysqli_stmt_prepare($stmt, $sql)) {
            die(mysqli_error($conn));
        } else {
            mysqli_stmt_bind_param($stmt, 's', $login);
            mysqli_stmt_execute($stmt);
            mysqli_store_result($conn);

            $resultCheck = mysqli_stmt_num_rows($stmt);

            //err == login name is already taken
            if ($resultCheck > 0) {
                die("login is taken");
            } else {
                $sql = "INSERT INTO users(user_login, user_email, user_pwd) VALUES (?, ?, ?);";
                $stmt = mysqli_stmt_init($conn);
                if (!mysqli_stmt_prepare($stmt, $sql)) {
                    die(mysqli_error($conn));
                } else {
                    $hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
                    mysqli_stmt_bind_param($stmt, 'sss', $login, $email, $hashedPwd);
                    mysqli_stmt_execute($stmt);
                }
                // insert_usertodb($conn, $login, $email, $pwd);
            }
        }

工作正常(`例如,用户插入的部分不会给出任何 mysqli 错误),但是,如果我尝试使用函数,用户插入的位置:

function insert_usertodb($conn, $user_login, $user_email, $user_pwd)
{
    $sql = "INSERT INTO users(user_login, user_email, user_pwd) VALUES (?, ?, ?);";
    $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($stmt, $sql)) { // <-- this is where the error happens
        // err_signup('sqlierror', '', '');
        die('sqlierror: ' . mysqli_error($conn));
    } else {
        //hash password
        $hashedPwd = password_hash($user_pwd, PASSWORD_DEFAULT);
        mysqli_stmt_bind_param($stmt, 'sss', $user_login, $user_email, $hashedPwd);
        mysqli_stmt_execute($stmt);
        // header("Location: ../signup.php?signup=success");
    }
}

并使用它代替插入用户的部分(在 else 分支之后 -> 函数在最后注释),mysqli 生成错误:

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

有没有什么原因,为什么具有相同代码的函数(比如从字面上复制部分(插入的地方)并且只是将变量名称更改为函数的参数)会产生不同步错误?而没有 func 的代码没有?

这是因为你在这里使用了错误的函数mysqli_store_result($conn);。您应该改用 mysqli_stmt_store_result($stmt);。这意味着您的代码没有按您希望的那样工作,并且存在性检查被破坏。这就是为什么使用 mysqli_stmt_num_rows().

是一个糟糕的主意

当它不在函数中时它起作用的原因是当您在 $stmt = mysqli_stmt_init($conn); 中为它分配不同的值时,您在 $stmt 对象上调用了析构函数。当调用析构函数时,它将在后台获取所有结果以“清理”线路。

如果为时不晚,请考虑改用 PDO。它更简单,你不会经常犯这样的错误。你用 mysqli 写的代码太冗长了。你不需要大部分。使用 PDO 会容易得多。