Pdo Try-Catch Usage in Functions

PDO try-catch usage in functions

Your implementation is just fine, and it'll work perfectly well for most purposes.

It's not necessary to put every query inside a try/catch block, and in fact in most cases you actually don't want to. The reason for this is that if a query generates an exception, it's the result of a fatal problem like a syntax error or a database issue, and those are not issues that you should be accounting for with every query that you do.

For example:

try {
$rs = $db->prepare('SELECT * FROM foo');
$rs->execute();
$foo = $rs->fetchAll();
} catch (Exception $e) {
die("Oh noes! There's an error in the query!");
}

The query here will either work properly or not work at all. The circumstances where it wouldn't work at all should not ever occur with any regularity on a production system, so they're not conditions that you should check for here. Doing so is actually counterproductive, because your users get an error that will never change, and you don't get an exception message that would alert you to the problem.

Instead, just write this:

$rs = $db->prepare('SELECT * FROM foo');
$rs->execute();
$foo = $rs->fetchAll();

In general, the only time that you'll want to catch and handle a query exception is when you want to do something else if the query fails. For example:

// We're handling a file upload here.
try {
$rs = $db->prepare('INSERT INTO files (fileID, filename) VALUES (?, ?)');
$rs->execute(array(1234, '/var/tmp/file1234.txt'));
} catch (Exception $e) {
unlink('/var/tmp/file1234.txt');
throw $e;
}

You'll want to write a simple exception handler that logs or notifies you of database errors that occur in your production environment and displays a friendly error message to your users instead of the exception trace. See http://www.php.net/set-exception-handler for information on how to do that.

Return values from function with pdo try/catch

To quote the documentation:

If the return is omitted the value NULL will be returned.

Since NULL is evaluated as false in most contexts, then the answer is no, this function will not return TRUE unless you explicitly state it. E.g.:

function add($db, $value) { 
try {
$stmt = $db->prepare("INSERT INTO table(value) VALUES (?);");
if ($stmt->execute(array($value))) {
return TRUE;
}
}
catch(PDOException $e) {
error_log($e->getMessage());
// Error handeling
}
// If we got here, the execute did not succeed
return FALSE;
}

How to use try-catch block for PDO

None of the answers here are wrong. But actually all three combined are the real answer.
You should definitely set

$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

as said by Cerad.

From now on every single issue about anything regarding database is thrown via exception of type PDOException. You just don't have to throw your own Exception as said by ladar because it's useless. Just take the ladar code and convert it into

 ...
$data = array();
$model = new BlogModel;

try{
$model->save(2,'test');
$data['result']['message'] = 'Settings saved';
$data['result']['status'] = 'success';
}catch(PDOException $e){
$data['result']['message'] = 'Could not save the settings';
$data['result']['status'] = 'error';
}

And do NOT throw anything by yourself.

Then a very nice way for debugging PDO queries is using the catch script linked by Basic that you can find here once again.

Combining this things togheter you'll have a flexible, clean and easy-debug way to catch all the errors that could come.

try catch in php pdo, doing it right way

There are too many questions and they are too generic. But in most cases:

  1. No way
  2. it's up to you, your app's logic and particular case. Say if there is water leak somewhere in the city is it expected to stop water supply system completely? Typically there is concrete module/part that does not make sense to process further once DB query fails. And only that module/part should exit/stop.
  3. it's better not doing your own wrapping around PDO. in most cases you will just make code harder to maintain without any real benefit.
  4. typically the best solution is to return some HTTP error(404 Not Found or 500 Internal Server Error) letting client code to know "sorry, you cannot get this information yet"; how client code will handle such an error - it depends on your client code's logic/flow

PDO: is try-catch necessary or not?

There is a security risk, but you don't need to add try/catch everywhere. The risk is that if you don't catch an exception then the error message from the exception (which could contain sensitive information) might be shown to users.

But as the documentation states, you can instead add an exception handler. By redirecting to a generic error message, you can avoid showing sensitive information from error messages to your users.

Setting a generic error handler would seem like a very sensible thing to do in any case. You don't want to be showing your users cryptic error messages. Even if you do go with the "try/catch everything" approach, it's difficult to be 100% sure that you've caught every possible exception that could occur, so the exception handler should still be used as a fallback.

PDO Exception Questions - How to Catch Them

You should look at the documentation. But If you dont find anything, you can add another catch :

<?php
try {
$stmt = $db->prepare("INSERT INTO tbl_user (id, name, password, question, answer) VALUES (NULL, :name, :password, :question, :answer)");
$stmt->bindValue(":name", $_POST['name']);
$stmt->bindValue(":password", $_POST['password']);
$stmt->bindValue(":question", $_POST['question']);
$stmt->bindValue(":answer", $_POST['answer']);
$stmt->execute();
echo "Successfully added the new user " . $_POST['name'];
} catch (PDOException $e) {
echo "DataBase Error: The user could not be added.<br>".$e->getMessage();
} catch (Exception $e) {
echo "General Error: The user could not be added.<br>".$e->getMessage();
}
?>

This must work because all exceptions of PHP plugins herits from the Exception native PHP class. (Since 5.0 if my memory is well).

use pdo in try/catch clause on the live site

That's a very good question, and - to my utter surprise - an extremely rare one. As though there are no developers running a live site around. And all the answers we have here is a mere proof for this surprising statement.

Should I use try/catch clause to write the PDO on the live site?

Of course no.

If I use try/catch clause to write it, all the errors details will appear on the web page.

It is not actually because of try-catch but because you're echoing them in that block yourself. But anyway, you shouldn't use that block either.

To prevent this happened, how do I know what errors are made without showing it on the web page?

You have to let them to be logged. To do so, you shouldn't use try-catch in the first place. Despite of all the wrong examples over the net, this operator has very little to do with reporting errors, and have to be used to handle errors, not to report them.

Surprisingly, PHP is very good at error logging. You won't believe me, but it can handle such a laborous task itself. Instead of wrapping each and every sql statement in try-catch, just leave them alone. In case of error, an exception will be thrown, yet uncaught exception is a fatal error. And for a live site you should have set error logging mode already. Means your PDO error will be logged as well.

As a result, to let yourself know what happened, all you need is to peek into error log.

In a nutshell, you shouldn't treat PDO error as something special. In either way, it's yet another error that happened in your code. Exactly the same as memory overflow error, or file not found error, or permission denied error. There is no special meaning in PDO errors and there is not a single reason to handle them in any special way. Just treat them as any other error in your site. In dev environment happily echo them on the screen for easy debugging, while on the live site disable error displaying and enable error logging, and you're set. I.e.

for a dev server:

error_reporting(E_ALL);
ini_set('display_errors',1);
ini_set('log_errors',1);

while for a live one

error_reporting(E_ALL);
ini_set('display_errors',0);
ini_set('log_errors',1);

When should you prepare and execute using `try` and `catch` using PDO?

Only when you have a very good reason to do so.

This doesn't apply to only PDO exceptions. The same goes for any exception. Only catch the exception if your code can recover from it and perform some other action instead.

Catching exceptions just to echo or return $e->getMessage(); is not a valid reason. Your code doesn't recover from the problem, you are just handicapping the exception.

A good example of when you might want to recover is if you are using database transactions and in case of failure, you want to rollback and do something else. You can call PDO::rollBack() in your catch and then make your code perform some alternative logic.

Try-catch is not a security measure. It has nothing to do with user input. It is used only in situations when you expect your code to fail, but you have a plan B to handle the situation.

For more information, you can read My PDO Statement doesn't work and the article PHP error reporting



Related Topics



Leave a reply



Submit