Reputation: 499
I get this error when I try to put the id
on button
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
. And the error is there in the else block where is users/bookAdd.php?user_id='. $res['user_id'] .'
Any idea how to fix this?
Upvotes: 1
Views: 938
Reputation: 41885
The error is already clear, you can't try to access indices in context of a PDOStatement object.
You can't just use ->query()
, and then try to access the values from the created object. 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();
Upvotes: 4