Asked  7 Months ago    Answers:  5   Viewed   32 times

I'm trying to work with PDO class on php but I have some trouble to find the right way to handle errors, I've wrote this code:

// $connection alreay created on a class which works with similar UPDATE statements
// I've simply added here trim() and PDO::PARAM... data type

$id = 33;
$name = "Mario Bros.";
$url = "";
$country = "jp";

try {

$sql = "UPDATE table_users SET name = :name, url = :url, country = :country WHERE user_id = :user_id";

$statement = $connection->prepare ($sql);

$statement->bindParam (':user_id', trim($id), PDO::PARAM_INT);
$statement->bindParam (':name', trim($name), PDO::PARAM_STR);
$statement->bindParam (':url', trim($url), PDO::PARAM_STR);
$statement->bindParam (':country', trim($country), PDO::PARAM_STR, 2);

$status = $statement->execute ();

} catch (PDOException $e) {
    print $e->getMessage ();

print $status; // it returns a null value, and no errors are reported


this portion of code doesn't report errors, but it simply doesn't work, the var $status at the bottom, return a null value.

can someone help me to find where I'm wrong?



PDO won't throw exceptions unless you tell it to. Have you run:

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

on the PDO object?

Wednesday, March 31, 2021
answered 7 Months ago

I found the answer:

$stmt = $db->prepare($query, [PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL]);

So the statement must be created with a PDO::CURSOR_SCROLL option


Wednesday, March 31, 2021
answered 7 Months ago

The user here claims that fetch() threw an exception. I'd be very careful in assuming that it doesn't or won't throw an exception just because they are typically thrown when you prepare or bind. This is a very good reason to put the call inside a try block. So to answer the question, in the highly unlikely event of failure, yes fetch() should throw an exception and in that one case it did. Now it will be interesting to see if there are other cases as well.

Saturday, May 29, 2021
answered 5 Months ago

Use $result = $q->fetchAll(PDO::FETCH_OBJ);

Wednesday, August 11, 2021
answered 3 Months ago

This is what PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION is for. Use it like this:

$pdo = new PDO(
            , 'user'
            , 'pass'

When used this way errors actually get thrown as exceptions. This means that should an error occur with fetch (or other methods using this pdo object) an exception will be thrown and the method won't actually return at all. This is a very effective way of handling errors in PDO. Now you know that if fetch returns a value no errors occured and therefore if it is false then the query returned no records.

Monday, August 23, 2021
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :