Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle PDO exceptions [duplicate]

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?

like image 344
vitto Avatar asked Jan 20 '10 19:01

vitto


People also ask

How do I stop duplicate emails in PHP?

php function createUser($email) { $sql = "SELECT * FROM vols2012 WHERE email='$email'" ; $result = mysql_query( $sql ) ; if( mysql_num_rows( $result ) > 0 ) { die( "There is already a user with that email!" ) ; }//end if function check_input($data, $problem='') { $data = trim($data); $data = stripslashes($data); $data ...

What is a PDO exception?

PHP Data Objects (or PDO ) are a collection of APIs and interfaces that attempt to streamline and consolidate the various ways databases can be accessed and manipulated into a singular package. Thus, the PDOException is thrown anytime something goes wrong while using the PDO class, or related extensions.

What is the purpose of PDO :: errorInfo () data?

PDO::errorInfo only retrieves error information for operations performed directly on the database. Use PDOStatement::errorInfo when a PDOStatement instance is created using PDO::prepare or PDO::query. Support for PDO was added in version 2.0 of the Microsoft Drivers for PHP for SQL Server.


1 Answers

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?

like image 179
Matchu Avatar answered Sep 22 '22 23:09

Matchu