-1

How is it possible to store result of a query into an array? For example, the following code will produce this error:

Fatal error: Uncaught Error: Cannot use object of type stdClass as array in C:\XAMPP\htdocs\php_test\test.php:50 Stack trace: #0 {main} thrown in C:\XAMPP\htdocs\php_test\test.php on line 50

const PATH_TO_SQLITE_FILE = 'my_db.sqlite';

$pdo = new \PDO("sqlite:" . PATH_TO_SQLITE_FILE);

$queryy = $pdo->query('SELECT Title, Format '
                . 'FROM Objects');


$arr = [];

        while ($row = $queryy->fetch(\PDO::FETCH_OBJ)) {
            $arr[] = [
                'Title' => $row['Title'], // Error occurs here. 
                'Format' => $row['Format']
            ];

        }

//echo $arr[1]->Title;

I've been stuck with this issue all morning and I haven't found the solution on Google. I hope someone can pinpoint what I'm not understanding.

Zhorov
  • 28,486
  • 6
  • 27
  • 52

1 Answers1

0

You are fetching an object and then trying to access it as if was an array. Either fetch an array PDO::FETCH_ASSOC or access the object $row->Title.

However, your code could be minimized to this:

$queryy = $pdo->query('SELECT Title, Format FROM Objects');

$arr = $queryy->fetchAll(PDO::FETCH_ASSOC);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87