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

When i try to use try catch, exception i get "Server error 500"

When i try to use the exception try catch statement, I always get the Server error 500. I have the exact code as in the video. It lets me do the first part when I var dump it but after i add the exception it breaks and gives me the error. Code:

try{
    $db = new PDO("mysql:host=localhost;dbname=shirts4mike;port=3306", "root", "PASSWORD");
    $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    $db->exec("SET NAMES 'utf8'");
} 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 "Query failed.";
    exit;

1 Answer

Kevin Kenger
Kevin Kenger
32,834 Points

Hey Ben,

If this is your exact code, it looks like you're missing the final closing bracket in your catch statement.

As for the 500 error, that's probably appearing because PHP errors are turned off on your server. If you have access to your php.ini file, you can go in there and add display_errors = on and that should allow you to see what errors your PHP code is throwing.

If you don't have access to that file, you can log in to your cPanel and check the error logs there. It should tell you what's going on with your PHP code and give the reason for it not working as you'd expect.

I just turned the setting on and its still giving me the 500 error, I also fixed my code. EDIT: Nevermind the bracket fixed my code it just wasnt updating, thanks!