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 PHP & Databases with PDO Getting Started With PDO Managing Errors

Alberto Caleia
Alberto Caleia
3,866 Points

Error when displaying preview

I get this message when displaying the preview. I tried as well on localhost on my computer and I get exactly the same fatal error.

Fatal error: Undefined class constant 'ATTR_ERRMODE_EXCEPTION' in /home/treehouse/workspace/index.php on line 9

This is the php code in my index.php

index.php
<?php

//remove before flight
ini_set('display_errors', 'On');

try {
  $db = new PDO('sqlite:./database.db');
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ATTR_ERRMODE_EXCEPTION);
} catch(Exception $e) {
  echo $e->getMessage();
  die();
}

?>

What am I missing or what causes the error? Thanks!

1 Answer

Vedran Brnjetić
Vedran Brnjetić
6,004 Points

PDO doesn't have ATTR_ERRMODE_EXCEPTION constant defined. The constant is ERRMODE_EXCEPTION, so you need PDO::ERRMODE_EXCEPTION.

So, this statement should look like this:

<?php

//remove before flight ini_set('display_errors', 'On');

try { 
    $db = new PDO('sqlite:./database.db'); 
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } 
catch(Exception $e) 
{ 
    echo $e->getMessage(); 
    die(); 
}

?>

Hope this helps

Alberto Caleia
Alberto Caleia
3,866 Points

Thanks! That was my mistake in the code, now working perfectly.