PHP's PDO database abstraction class offers a better way to connect to databases than the mysql_* etc style functions, or using a 3rd party database library. This post looks at handle errors when connecting and a follow up post later this week will look at how to check for errors when running individual queries after a connection has been successfully established.
How to connect to the database
Everything in this post is covered in the PHP manual but I'm adding a few extra notes here about what to look for when connecting and what the default behaviors are. The way to connect to a database with PDO is like so:
$dsn takes the form along the lines of this: "mysql:host=[HOSTNAME];dbname=[DATABASE NAME]" by subsituting the correct host and database. The dsn options aren't that well explained or covered in the PHP manual (at least I haven't been able to find concise documentation) so I may do a follow up post looking at the dsn options as well.
Wrap the attempt to connect within a try..catch block
If the database connection could not be established then it will silently fail and no error message will be displayed. The PHP script will also continue to run. This is not at all desirable so it is important to always wrap a PDO connection within a try..catch block like so:
Getting the error message
The PDO class has a couple of error code functions: errorCode() and errorInfo() but these are not accessible if the connection could not be established. Instead, using the PDOException object's getCode(), getMessage() etc methods. Read my earlier "PHP Exceptions - available information" post for more details about the types of information available.
From my own testing, $e->getCode() always appears to return 0 so it's $e->getMessage that you will need to use for reporting or emailing to the webmaster. For example:
Example error messages include:
- SQLSTATE[HY000] [2005] Unknown MySQL server host 'fakehost' (1)
- SQLSTATE[42000] [1049] Unknown database 'fakedb'
- SQLSTATE[28000] [1045] Access denied for user 'fakeuser'@'localhost' (using password: YES)
Conclusion and future posts
This should be everything you need to deal with catching errors when attempting to connect to the database using PDO. In future posts I'll look at more of the options available for the DSN and looking for errors when running SQL queries.
0 comments:
Post a Comment