0

I have a script that I am updating by replacing the inline mysql queries with PDO prepared statements and queries. When the query is correct or returns a result, it works fine. However, when there is an error in the query statement try/catch dies not work. For example, I used this test code:

$query = $this->dbh->prepare('SELEC menu_item, hyperlink, admin FROM top_menu;');
    try
    {
            $query->execute();
        $row = $query->fetch(PDO::FETCH_ASSOC));
                    die("success");

    }

    catch(Exception $e)
    {
        die("fail");        
    }

The query is wrong ("SELEC" instead of "SELECT"), so the flow of the script should go into the exception/error brackets, and yet it doesn't; I keep getting "success". I've tried catch(PDOException $e) instead of catch(Exception $e) with the exact same results.

What am I doing wrong, and how can I fix this? Thanks.

j0k
  • 22,600
  • 28
  • 79
  • 90
Anonymous
  • 41
  • 2
  • 5

2 Answers2

1

A similar problem has been answered here, 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.

Community
  • 1
  • 1
Okipa
  • 551
  • 4
  • 18
-1

For PDO's fetch() on failure FALSE is returned. No exception is thrown.

See: http://php.net/manual/en/pdostatement.fetch.php

Aleksey Korzun
  • 680
  • 4
  • 7