我正在尝试从选择查询中获取一列,但我一直收到此错误
Notice: Trying to get property of non-object
SQL
$row = $conn->query("SELECT * from user where name='".$username."' and password='".$password."'");
$row->setFetchMode(PDO::FETCH_ASSOC);
$row->execute();
$results = $row->fetchAll();
$count = $row->rowCount();
$get_user_role = $row["name"];
echo $get_user_role;
答案 0 :(得分:0)
据我了解,您希望从该SQL查询中获取一行,并通过查看代码来执行fetchAll
,该操作将返回false
或带有指针的结果数组那么必须在循环中使用,即while
。
我会做些不同的事情(,然后向您介绍prepared statements ):
$row = $conn->query("SELECT * from user where name = :name and password = :password;");
$row->setFetchMode(PDO::FETCH_ASSOC);
$row->execute([
'name' => $username,
'password' => $password
]);
$result = $row->fetch();
if($result !== false) {
$count = $row->rowCount();
$get_user_role = $result["name"];
echo $get_user_role;
} else {
echo 'User not found or does not exist.';
}