0

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?

2
  • having an empty result set will not be catched, just handle it separately Commented Mar 30, 2016 at 1:38
  • "Exceptions if database rows don't exist" -- You would have to throw your own exception because that doesn't throw one by default. Commented Mar 30, 2016 at 1:38

1 Answer 1

1

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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.