PDO从选择查询中获取一列

时间:2018-11-09 15:30:01

标签: php mysql pdo

我正在尝试从选择查询中获取一列,但我一直收到此错误

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;

1 个答案:

答案 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.';
}