在布林值上呼叫 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??