Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.


    $db = new PDO("mysql:host=localhost;dbname-shirts4mike;port=8889", "root", "root");
    $db->exec("SET NAMES 'utf8'");
} catch (Exception $e) {
    echo "Could not connect to the database.";

try {
    $results = $db->query("SELECT name, price FROM products");
    echo "Our query ran successfully.";
} catch (Exception $e) {
    echo "Query failed.";

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,005 Points

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