18

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:

<?php
// $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 = "http://nintendo.com";
$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?

0

2 Answers 2

48

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?

Sign up to request clarification or add additional context in comments.

5 Comments

@Matchu: This is the default behavior? Since when?!
Since I last built a database class a month ago or so. At least in my environment, silent mode was default.
Found it - us3.php.net/manual/en/pdo.error-handling.php - "PDO::ERRMODE_SILENT - This is the default mode."
@Matchu: Yeah you're right, thanks. Still PDO::__construct() throws a PDOException if the attempt to connect to the requested database fails.
Matchu, thanks a ton, I was already ripping off my hair because I could not get the try / catch to run. You made my day!
1

You can add the attribute one time while you connect you mysql.

function connect($dsn, $user, $password){
    try {
        $dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
        exit;
    }
    }

Thanks

3 Comments

Nice! What about PDO::ERRMODE_EXCEPTION?
Same way PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.