警告 :: 无效对象或资源 mysqli_stmt。什么意思和解决方案?

warning :: invalid object or resource mysqli_stmt. What is the meaning and solution(s)?

以下代码抛出了神秘的警告。我不明白他们的意思。这些错误表明什么以及如何消除它们?

require "conn.php";
$q = mysqli_stmt_init($dbconn);
$query = "SELECT users.userid FROM users WHERE users.email = ? ";
mysqli_stmt_prepare($q, $query);
mysqli_stmt_bind_param($q, "s", $email);
mysqli_stmt_execute($q);
$result = mysqli_stmt_get_result($q);
if (mysqli_num_rows($result) == 0) {
    $q = mysqli_stmt_init($dbconn);
    $query = "INSERT INTO users ( users.first_name, users.last_name, users.mobile_no, users.email, users.password, users.reg_date) 
        VALUES (? ,? ,? ,? ,? ,NOW() )";
    mysqli_stmt_prepare($q, $query);
    mysqli_stmt_bind_param($q, "sssss", $first_name, $last_name, $mobile_number, $email, $password);
    mysqli_stmt_execute($q);
    if (mysqli_stmt_affected_rows($q) == 1) {
        echo "data inserted <br>";
        foreach ($_POST as $key => $val) {
            echo "$key - - - > $val <br>";
        }
    }
} else {
    echo "email is already registered";
}

每当我 运行 此代码块出现以下警告时

Warning: mysqli_stmt_bind_param(): invalid object or resource mysqli_stmt in /storage/emulated/0/htdocs/registration_process.php on line 66

Warning: mysqli_stmt_execute(): invalid object or resource mysqli_stmt in /storage/emulated/0/htdocs/registration_process.php on line 67

Warning: mysqli_stmt_get_result(): invalid object or resource mysqli_stmt in /storage/emulated/0/htdocs/registration_process.php on line 68

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in /storage/emulated/0/htdocs/registration_process.php on line 70 

这里的问题比较特殊。这听起来无关紧要,但此错误消息是 不可靠语法变体 的结果。

与对象语法相比,过程性 mysqli 语法不仅过于冗长,而且具有欺骗性,引发错误而不是在真正发生时,但已经为时已晚,更不用说此错误消息的神秘性质了。

您的查询存在一些问题,您需要从 MySQL 获取 真实 错误消息 ,如中所述这个 answer 但是为了实现它你必须改变语法。

外卖:解决你的问题

  1. 重写您的 conn.php,如我的 article 所示,以设置正确的连接设置
  2. 重写你的过程 mysqli 到对象语法,例如

    $query = "SELECT userid FROM users WHERE email = ?";
    $stmt = $dbconn->prepare($query);
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();
    
  3. 获取真正的错误信息

  4. 如果错误已经很明显,那么就修复它,否则google为了更好的解释

然后您就可以解决问题了。