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

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