我的category
表包含cat_id
,cat_name
,user_id
和time_stamp
列。
我正在尝试回显cat_name
匹配user_id
的{{1}}个10
行,而是回显表中的所有cat_names
。你能告诉我为什么好吗?
正确查询user
表:user_id
是username
的对应值:
//here is the user_id, which is the corresponding user_id for username Joe Blogs
echo $user_id;
我无法理解为什么我的代码会回显整个表格中的所有cat_names
- 而不仅仅是那些与cat_names
相关联的user_id
。
这是我的代码:
$Number = "Joe Blogs";
$query = "SELECT * FROM user WHERE username = ?";
$stmt = $con->prepare($query) or die(mysqli_error($con));
$stmt->bind_param('s', $Number) or die ("MySQLi-stmt binding failed ".$stmt->error);
$stmt->execute() or die ("MySQLi-stmt execute failed ".$stmt->error);
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
//get the corresponding user_id in the row
$user_id = $row["user_id"];
//here is the user_id, which is the corresponding user_id for username Joe Blogs
echo $user_id;
}
$sql = "SELECT cat_name FROM category WHERE $user_id = ?";
$stmt2 = $con->prepare($sql) or die(mysqli_error($con));
$stmt2->bind_param('i', $user_id) or die ("MySQLi-stmt binding failed ".$stmt2->error);
$stmt2->execute() or die ("MySQLi-stmt execute failed ".$stmt2->error);
$result2 = $stmt2->get_result();
while ($row[] = $result2->fetch_assoc()) {
$data = $row;
$json = json_encode($data);
}
echo $json;
答案 0 :(得分:2)
如果仔细观察这一行
$sql = "SELECT cat_name FROM category WHERE $user_id = ?";
// specifically here ^
将等同于
SELECT cat_name FROM category WHERE 10 = 10
由于10 = 10
始终为true,因此会返回表格中的所有行
像这样纠正这条线
$sql = "SELECT cat_name FROM category WHERE user_id = ?";