php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #56559 prepare returns null on error instead of throwing exception
Submitted: 2005-09-21 12:42 UTC Modified: 2005-09-23 10:21 UTC
From: danajp at gmail dot com Assigned:
Status: Not a bug Package: PDO_PGSQL (PECL)
PHP Version: 5.0.3 OS: Gentoo Linux
Private report: No CVE-ID: None
 [2005-09-21 12:42 UTC] danajp at gmail dot com
Description:
------------
When calling PDO::prepare() on a query that is in some way invalid (references a table that doesn't exist, has a syntax error, etc), prepare() quietly returns null instead of returning a PDOStatement object or throwing an exception. This makes it awfully hard to debug anything, since the only error message you get is a "null or not an object" error when you call execute() on what you think is a PDOStatment.

prepare() should throw an exception when the sql query is malformed.

Reproduce code:
---------------
<?php

try {
    $db = new PDO("pgsql:dbname=application user=application_php password=app");
} catch (PDOException $e) {
    echo "error connecting to database: " . $e->getMessage();
    exit();
}

$query = "select * from some_non_existant_table";

$stmt = $db->prepare($query);


echo 'class name of $stmt is [' . get_class($stmt) ."]\n";

?>

Expected result:
----------------
should throw an exception

Actual result:
--------------
prints:

class name of $stmt is []

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2005-09-23 10:21 UTC] edink at emini dot dk
You need to set the error mode before prepare:

$db->setAttribute(PDO_ATTR_ERRMODE, PDO_ERRMODE_EXCEPTION);
 [2005-09-23 10:21 UTC] wez@php.net
If you want PDO to throw exceptions, you need to ask it to do that:
$db->setAttribute(PDO_ATTR_ERRMODE, PDO_ERRMODE_EXCEPTION);

See http://docs.php.net/en/ref.pdo.html#pdo.error-handling for more info.
 
PHP Copyright © 2001-2022 The PHP Group
All rights reserved.
Last updated: Mon Oct 03 12:05:54 2022 UTC