[英]Cannot use object of type PDOStatement as array
I want to check if some column of specify user is holding a value higher than 0. 我想检查指定用户的某些列是否保持高于0的值。
Problem 问题
When doing the query, and then executing it , Im getting this error: 在执行查询, 然后执行它时 ,我收到此错误:
Fatal error: Cannot use object of type PDOStatement as array in C:\xampp\htdocs\recover\admin\create.php on line 40
My code (The query + execute): 我的代码(查询+执行):
if (isset($_SESSION['user'])) {
$admin = $CONNECT_TO_DATABASE->prepare("SELECT * FROM admin WHERE username = :username");
$admin->bindValue(':username', $_SESSION['user']);
$admin->execute();
Line of error (40): 误差线(40):
if ($settings['create_admins'] > 0 || $admin['super_admin'] > 0 ) {
Question: 题:
Why am I getting this error? 为什么我收到此错误? How do I fix it?
我如何解决它?
I tried doing this: 我试过这样做:
$admin = $CONNECT_TO_DATABASE->prepare("SELECT * FROM admin WHERE username = :username");
$admin = $admin->bindValue(':username', $_SESSION['user']);
$admin = $admin->execute();
and getting another error: 并得到另一个错误:
Fatal error: Call to a member function execute() on a non-object in C:\xampp\htdocs\recover\admin\create.php on line 38
Thanks! 谢谢!
EDIT: I need the ->fetch object, but I have just done this, and got rid of the errors.. But it doesn't affect? 编辑:我需要 - >获取对象,但我刚刚完成了这个,并摆脱了错误..但它不影响? I mean I am echoing that row, and it gives me a null (nothing).
我的意思是我回应那一行,它给了我一个空(没有)。 Why?
为什么?
$admin = $CONNECT_TO_DATABASE->prepare("SELECT * FROM admin WHERE username = ".$_SESSION['user']."");
$admin = $admin->fetch();
From: 从:
$admin = $CONNECT_TO_DATABASE->prepare("SELECT * FROM admin WHERE username = :username");
[...]
if ($settings['create_admins'] > 0 || $admin['super_admin'] > 0 ) {
$admin
is of type PDOStatament
which is a class and not an array. $admin
是PDOStatament
类型,它是一个类而不是数组。 Therefore you can't call the []
operator on it. 因此,您无法调用
[]
运算符。
Also you should really not alway assign $admin
to the return result of every method because most of the PDOStatament
's methods return boolean values: 此外,您应该不会将
$admin
分配给每个方法的返回结果,因为大多数PDOStatament
的方法都返回布尔值:
$admin = $CONNECT_TO_DATABASE->prepare("SELECT * FROM admin WHERE username = :username");
$admin->bindValue(':username', $_SESSION['user']);
$admin->execute();
To retrieve the super_admin
column from the admin
table you should add (after the execute()
statement): 要从
admin
表中检索super_admin
列,您应该添加(在execute()
语句之后):
$result = $admin->fetch(PDO::FETCH_ASSOC);
which will populate (hopefully, it depends on what's the table schema) $result['super_admin']
. 将填充(希望,它取决于表模式)
$result['super_admin']
。
try this: 尝试这个:
$sql = "SELECT * FROM admin WHERE username = ?";
$stmt = $CONNECT_TO_DATABASE->prepare($sql);
$stmt->execute(array($_SESSION['user']));
$admin = $stmt->fetch();
if($admin) {
//do something if query returns row(s)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.