简体   繁体   中英

Cannot use object of type PDOStatement

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'] .' 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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM