在布尔值上调用 fetch assoc

如果你得到这样的错误:

Fatal error: Call to a member function fetch_assoc() on boolean in C:\xampp\htdocs\stack\index.php on line 7

其他变体包括以下内容:

mysql_fetch_assoc() expects parameter 1 to be resource, boolean given...

这些错误意味着你的查询(这是 PHP / MySQL 错误)或你的引用有问题。上述错误由以下代码生成:

$mysqli = new mysqli("localhost", "root", "");
    
$query = "SELCT * FROM db"; // notice the errors here
$result = $mysqli->query($query);
    
$row = $result->fetch_assoc();

为了修复这个错误,建议改为使用 mysql 抛出异常:

// add this at the start of the script
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

然后,这将使用这个更有用的消息抛出异常:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELCT * FROM db' at line 1

另一个会产生类似错误的例子就是你只是将错误的信息提供给 mysql_fetch_assoc 函数或类似的:

$john = true;
mysqli_fetch_assoc($john, $mysqli); // this makes no sense??