Development Tools Using PHP with MySQL Querying the Database with PHP Querying the Database

William J. Terrell
William J. Terrell
17,403 Points

Cannot connect to the Database

In the last video, my code connected to the database just fine, but is now throwing the first exception ("Could not connect to the database").

My code is as follows:

<?php

try {
    $db = new PDO("mysql:host=localhost;
                            dbname=shirts4mike;
                            port=3306;",
                            "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 "Query was successful.";
} catch ( Exception $e ) {
    echo "Query could not be processed.";
    exit;
}

When I remove this code:

    $db -> setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    $db -> exec("SET NAMES 'utf-8'");

everything seems to work fine, but I cannot see what I am doing wrong with that bit of code.

Any assistance would be appreciated.

Thanks!

1 Answer

Here is my code from that project. It worked:

<?php
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");

The only difference I see is the white space. Try removing the spaces on both sides of the -> first. If that does not work, then remove the white space around the rest of the stuff.

Let me know what the answer is because I am very curious.

William J. Terrell
William J. Terrell
17,403 Points

I tried removing the white space from around the arrows, but that still didn't work, yet it works just fine when I paste in the code that you provided.

Aha! In my code, I have it written as "utf-8", whereas in your code, it is "utf8" (without the hyphen), so it must be catching an error in the database itself, and since we have that ERRMODE thing set up, it throws the Exception in that "catch" block right after it (at least I think that's how that ERRMODE thing works). :)

Thanks!

I should have seen the hyphen. I read that we should really use utf8mb4. I am not sure why that is, though. I think it is a security issue.