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 Querying the Database

Why is my query failing?

I can connect to the database easily enough, but I'm catching an exception when I query the database.

<?php

try{
    $db = new PDO("mysql:host=localhost;dbname-shirts4mike;port=8889", "root", "root");
    $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 name, price FROM products");
    echo "Our query ran successfully.";
} catch (Exception $e) {
    echo "Query failed.";
    exit;
}

I get a result of "Query failed." when I refresh database.php

Edit -- I was able to successfully run the query once I changed 'products' to 'shirts4mike.products'. Am I missing something or did the syntax change for this?

Are you shure about the port? Normally is 3306, do var_dump($db); to see the conection state.

2 Answers

Also, dbname-shirts4mike is not right. It should be dbname=shirts4mike. Also, your password may be root, but it is more likely "".

jason chan
jason chan
31,009 Points

I would delete the port, and password if your password is blank.