我如何解决PHP致命错误:调用成员函数fetch_assoc()?

时间:2016-09-04 12:10:02

标签: php mysql

我有两个表,usercategory

用户表:

enter image description here

类别表:

enter image description here

user_id表中的

user是主键,也是category表中的外键。

我想显示John Grisham的标题列表,但我得到了:

Fatal error: Call to a member function fetch_assoc() on boolean in C:\wamp64\www\listprimarykeys.php on line 16

第16行是:

while($rows = $resultSet->fetch_assoc())

这是我的代码。我的SELECT声明好吗?

<?php

$username = "John Grisham";

require_once('dbConnect.php');

$resultSet = $mysqli->query("SELECT cat_name FROM category INNER JOIN user ON category.user_id = user.user_id WHERE user.username = $username");

while($rows = $resultSet->fetch_assoc())

    {
        $user_id = $rows['cat_name'];
        echo "<p>categories are $user_id";

    }

?>

1 个答案:

答案 0 :(得分:3)

我嘲笑这个问题。如果您遇到一个查询问题,则必须在查询字符串中的变量$username之前和之后添加两个引号

此代码权限:

<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$username = "ali" ;
$sql = "SELECT catname FROM category INNER JOIN user ON category.user_id = user.id WHERE user.username = '$username' ";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo " Name: " . $row["catname"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();


?>

如果在 MySQLi 中使用此方法更好地完成此工作以防止SQL注入:http://php.net/manual/en/mysqli.prepare.php