当我尝试将id
置于按钮
Fatal error: Cannot use object of type PDOStatement as array...
代码在哪里是错误就是这个
$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();
我尝试的是当用户登录时,如果没有书籍向他显示按钮Create book
。并且错误存在于else块中,users/bookAdd.php?user_id='. $res['user_id'] .'
任何想法如何解决这个问题?
答案 0 :(得分:4)
错误已经很明显,您无法在PDOStatement对象的上下文中访问索引。
您不能只使用->query()
,然后尝试从创建的对象中访问值。您还没有获取结果。
您需要正确获取结果:
$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();