[英]Cannot use object of type PDOStatement
I get this error when I try to put the id
on button 当我尝试将id
放在按钮上时出现此错误
Fatal error: Cannot use object of type PDOStatement as array...
The code where is the error is this 错误在哪里的代码是这里
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = "SELECT * FROM books where user = '".$_SESSION['level']."'";
if($res = $pdo->query($q))
{
if($res->fetchColumn() > 0)
{
foreach($pdo->query($q) as $res)
{
echo '<a href="users/books.php?user_id='. $res['user_id'] .'"> '.$res['name'].' </a>';
}
}
else
{
echo '<a href="users/bookAdd.php?user_id='. $res['user_id'] .'">Create Book</a>';
}
}
Database::disconnect();
What I trying is when user log if there is no books to show him button Create book
. 我要尝试的是当用户登录时如果没有书可显示给他,则按钮Create book
。 And the error is there in the else block where is users/bookAdd.php?user_id='. $res['user_id'] .'
错误在else块中存在,那里是users/bookAdd.php?user_id='. $res['user_id'] .'
users/bookAdd.php?user_id='. $res['user_id'] .'
Any idea how to fix this? 任何想法如何解决这个问题?
The error is already clear, you can't try to access indices in context of a PDOStatement object. 该错误已经很明显,您无法尝试在PDOStatement对象的上下文中访问索引。
You can't just use ->query()
, and then try to access the values from the created object. 您不能只使用->query()
,然后尝试从创建的对象访问值。 You haven't fetch the results yet. 您尚未获取结果。
You need to fetch the results properly: 您需要正确获取结果:
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prep the statement
$q = $pdo->prepare("SELECT * FROM books WHERE user = :level");
$q->bindParam(':level', $_SESSION['level']); // bind it
$q->execute();
// fetch the results
$results = $q->fetchAll(PDO::FETCH_ASSOC);
if(count($results) > 0) {
foreach($results as $res) {
echo '<a href="users/books.php?user_id='. $res['user_id'] .'"> '.$res['name'].' </a>';
}
} else {
echo '<a href="users/bookAdd.php">Create Book</a>';
}
Database::disconnect();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.