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

PDO query not executing

Instead of querying the database, and returning results, I just get my SQL string fed back to me.

<?php 

require_once("/../inc/config.php");

    try{
            $db = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";port=" . DB_PORT,DB_USER,DB_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 * FROM `prism employees`");
    } catch (Exception $e) {
        echo "Data could not be retrieved from the database.";
        exit;
    }

and this is what I get when I run through Firefox

object(PDOStatement)#2 (1) { ["queryString"]=> string(31) "SELECT * FROM prism employees" }

1 Answer

Hi Matthew,

Is doesn't look like you have anything in place to display the data, unless it is in a part of the code we can't see. You would need to add something like this to echo out a single value. For example if one of the columns in your prism employees table was called "name":

<?php 
$employee = $results->fetchAll(PDO::FETCH_ASSOC);   

echo $employee["name"];
?>

I'm not sure what your goal is, but there are all kinds of different ways you can loop through and display the data.

Sorry, I've been using var_dump to drop the table on to a page, which worked in the past but now is throwing back my SQL script. This is the bit of code I've been using to display my data.

<?php echo "<pre>"; var_dump($results); ?>

Thanks for the help so far! edit I'm just trying to get this table to display all the data in the table on this page.