helloworld
helloworld

Reputation: 527

PDO exception not catched when accessed using class

I'm using the following class in order to create and access a PDO db connection:

class DBCxn {
    // What Data Source Name to connect to?
    public static $dsn='mysql:host=localhost;dbname=dbname';
    public static $user = 'root';
    public static $pass = 'root';
    public static $driverOpts = null;

    // Internal variable to hold the connection
    private static $db;
    // no cloning or instantiating allowed
    final private function __construct() {}
    final private function __clone() {}

    public static function get() {
        // Connect if not allready connected
        if (is_null(self::$db)) {
            self::$db = new PDO(self::$dsn, self::$user, self::$pass, self::$driverOpts);       
        }

    // Return the connection
    return self::$db;
    }

}

When I try to access it in the following manner and the supplied query fails (tes instead of test) it will not throw an exception:

$db = DBCxn::get();


try {

    foreach($db->query('SELECT * from tes') as $row) {
        print_r($row);
    }
    $db = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

The code returns the warning: Invalid argument supplied for foreach()

Why isn't the exception being catched?

Upvotes: 2

Views: 150

Answers (1)

jbafford
jbafford

Reputation: 5668

Warnings and errors generated by PHP (such as the invalid argument warning you are getting) are not always exceptions. Even when they are, you're specifically catching PDOException, and an invalid argument isn't a PDOException.

PDO::query normally returns false if there is an error in the query (hence why foreach is complaining about an invalid argument). To cause an exception to be raised instead, you should also call

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

before making your query.

Upvotes: 2

Related Questions