PHP Using PHP with MySQL Connecting PHP to MySQL Handling Exceptions

Elizabeth Frazier
Elizabeth Frazier
10,187 Points

Can't prevent error text from echoing to the screen when using a try-catch block.

In the video Randy writes the code to instantiate a new database connection object ($db) as a member of the PDO class. He then places this code in a try-catch block. Finally, to force the code to throw an error, he purposely changes "host=localhost" to "host=brokenhost"

<?php

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

echo "Woo-hoo!";

My issue is that when Randy does this, only the "Could not.." string is echoed to the screen:

See his results

When I run the same code (except for the password string, which is empty), a warning is echoed to the screen before the "Could not..." string:

See my results

How can I keep this warning from echoing to the screen?


UPDATE: It seems that this behavior only happens when the "host=localhost" part of the connection string is incorrect, but I would still like to know how to keep that warning from echoing.

2 Answers

Hello,

That warning is suppose to be there. It's PHPs way of telling you that your script will probably not work. Since PDO is a PHP library, the PHP parser will error, warn, or notice any type of problems that may arise. Usually warnings will not stop the page from loading (only errors do). If you want to stop displaying warnings, open up your php.ini file (which can be located by going into your local web server's configuration and choosing to edit the ini file) and go down to the "Error handling and logging" section and using the following:

error_reporting = E_ALL & ~E_NOTICE & ~E_WARNING

Once you do this, restart your web server and you should be good. Let me know if this fixes your problem.

Cheers!

Elizabeth Frazier
Elizabeth Frazier
10,187 Points

Thanks, that worked just fine. I'll leave the warnings in place for the future, but it's good to know how to exercise this option.