我有两个表,user
和category
用户表:
类别表:
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";
}
?>
答案 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