Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Using PHP with MySQL Querying the Database with PHP Retrieving the Result Set

nicholas maddren
nicholas maddren
12,793 Points

Fatal error: Call to a member function fetchAll() on a non-object

Hey guys I've been following Randy's video and everything was going great until I got to this step, can you see anything wrong with my script?

<?php

try {
    $db = new PDO("mysql:host=localhost;dbname=database","username","password");
    $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    $db->exec("SET NAMES 'utf8'");
} catch (Exception $e) {
    echo "Could not connect to the database.";
    exit;
}

try {
    $db->query("SELECT Make, Model FROM import ORDER BY Make ASC");
    echo "Successful.";
} catch (Exception $e) {
    echo "Error.";
    exit;
}
echo "<pre>";
var_dump($results->fetchAll());

?>

Any idea what I'm doing wrong? I'm getting this error:

Fatal error: Call to a member function fetchAll() on a non-object in /home/dealerby/public_html/database.php on line 21

Thanks

1 Answer

Hi NIcholas

You are calling fetchAll method on $results but have not assigned the return value from $db->query to $results.

try this

<?php

try {
    $db = new PDO("mysql:host=localhost;dbname=database","username","password");
    $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    $db->exec("SET NAMES 'utf8'");
} catch (Exception $e) {
    echo "Could not connect to the database.";
    exit;
}

try {
    $results=$db->query("SELECT Make, Model FROM import ORDER BY Make ASC");
    echo "Successful.";
} catch (Exception $e) {
    echo "Error.";
    exit;
}
echo "<pre>";
var_dump($results->fetchAll());

?>