Ch: 003 Error handling - heikijapan/php-book2 GitHub Wiki
There are several ways of error handling in PHP. TRY & CATCH block is the most used one.
- It can cover large code blocks and be even wrapped or span over IF blocks.
- Instead of one big block, it would be better to have smaller blocks in that way it will be easier to define the cause of an error.
- It is smart to have one
try & catchprotect PDO connection block and then one individualtry & catchfor every CRUD operation. - To define your own error blocks and messages
Throwableis used.
try {
$pdo = new PDO('mysql info etc');
$stmt = $pdo->prepare('SELECT * FROM `my_database_table` WHERE `id` < 5 ASC');
$stmt->execute()
} catch (PDOException $e) {
// This logs errors into server log file, DIR can be found using phpinfo()
// If you want to use your own log file, then use log_errors();
error_log($e->getMessage());
$msg = 'Something went wrong! Cannot connect to MySQL database`;
}