I try to handle or catch possible errors with PHP/MySQL for security reasons and would like to know if I'm doing it right.
The first case, connection: I use it as a function and call it always when I need a database connection:
function pdo () {
try {
$pdo = new PDO('mysql:host=localhost;dbname=dbname', 'user', 'pw');
}
catch(PDOException $e) {
header("Location: handle_error.php");
exit;
}
return ($pdo);
}
The second case, a query: I am not sure how to handle it. I put all prepared statements in IF
conditions but that's pretty awkward. And what about $stmt->execute
? This could also fail or not? To handle this also in an if
condition can really get confusing. I hope there is a better way to go.
if ($stmt = $pdo->prepare("SELECT a FROM b WHERE c = :c")) {
$stmt->execute(array(':c' => $c));
$result = $stmt->fetch();
echo 'All fine.';
}
else {
echo 'Now we have a problem.';
}
Later, I would like to report the errors properly so the admin can check what's going on.