Php:为什么我的代码会回显表中的所有值而不仅仅是这些值的子集?

时间:2018-03-24 23:16:39

标签: php

我的category表包含cat_idcat_nameuser_idtime_stamp列。

我正在尝试回显cat_name匹配user_id的{​​{1}}个10行,而是回显表中的所有cat_names。你能告诉我为什么好吗?

正确查询user表:user_idusername的对应值:

    //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;

1 个答案:

答案 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 = ?";