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

Querying the Database - Having trouble connecting...

This worked fine:

<?php 

try {
    $db = new PDO("mysql:host=localhost;dbname=shirts4mike;port=3308","root");
    var_dump($db);
} catch (Exception $e) {
    echo "Could not connect to the database.";
    exit;
}

    echo "YAY!";

?>

This wont let me get past the first try catch block. I get the Exception message, "Could not connect to the database."

<?php 

try {
    $db = new PDO("mysql:host=localhost;dbname=shirts4mike;port=3308","root");
    $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    $db->exec("SET NAMES 'utf-8'");
} 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 "Data could not be retrieved from the database";
}

?>

Yes, I changed the port number so I could also run Workbench on my machine, and no, I currently do not have a password.

Can anyone see if there is something I have done wrong?

2 Answers

Hi Aaron,

The only problem I see is you have quotes around utf-8, aside from that your code doesn't appear to have any other errors.

$db->exec("SET NAMES utf-8");

In saying that anytime you have an exception it's best practice to see what the message was for debugging purposes such as this.

<?php 

try {
    $db = new PDO("mysql:host=localhost;dbname=shirts4mike;port=3308","root");
    $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    $db->exec("SET NAMES 'utf-8'");
} catch (Exception $e) {
    echo "Could not connect to the database.<br><br>" . $e->getMessage();
    exit;
}

Hi Chris,

Thank you very much for that valuable tip. I will use that in the future.

Following your advice, and doing a bit of digging, I found that 'utf-8' wasn't being recognized, and that it should be changed to 'utf8'. Once that was done, all was good. I understand it has something to do with the MySQL config file that used that particular syntax.

Thanks again!!