kmancusi
kmancusi

Reputation: 571

PHP database error handling in try-catch block using PDO connection

I am working on an exercise that involves using a try-catch block to throw Exceptions if database rows don't exist. Here's an example of a read() function:

class Manager {
    private $desc;
    private $id;
    private $newDesc;
    public function read($id) {
        $db = new PDO('mysql:host=localhost; dbname=database', 'root', '');
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        try {
            $sql = "SELECT * FROM table where `id` = :id_val";
            $query = $db->prepare($sql);
            $query->bindParam(":id_val", $id);
            $query->execute();
            $results = $query->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            echo "Could not return specified row! <br />";
            echo $e->getMessage();
        }
        echo "<pre>";
        print_r($results);
        echo "</pre>";
   }
}

Outside the class I run:

$manager = new Manager();
$manager->read(44); // this is an id that IS NOT an existing record

My browser shows Array()
Am I placing the wrong statements into the try-catch, or is it something else altogether?

Upvotes: 0

Views: 1052

Answers (1)

tanaydin
tanaydin

Reputation: 5316

It's normal behaviour, "try catch" statements catches errors, exceptions... No record given id is not an error. If you want to check there is record or not you can count your result set with

count($results);

If this count is bigger than 0, it exists.

Upvotes: 1

Related Questions