penitent_tangent
penitent_tangent

Reputation: 772

PDOException doesn't fire on statement execution failure

I'm dabbling with PHP in Google App Engine (and learning about database design and PDO at the same time). Here's a bit of data insertion code which isn't working:

<html>
<body>
Collection Protocol
<?php

$db = null;

  try{
     $db = new pdo('mysql:unix_socket=/cloudsql/myidhere:cloudsql;dbname=mydb-schema', 'root', '');
  }catch(PDOException $ex){
      die(json_encode(
          array('outcome' => false, 'message' => $ex->getMessage())
          )
      );
  }



try {

    $stmt = $db->prepare('INSERT INTO observations(observation_remote_id_fk, observation_dimension_id_fk, metric) VALUES (:remote_id, :dimension_id, :metric)');
    $stmt->execute(array(':remote_id' => htmlspecialchars('1'), ':dimension_id' => htmlspecialchars('1'), ':metric' => htmlspecialchars('1')));

} catch (PDOException $ex2) {
      die(json_encode(
          array('outcome' => false, 'message' => $ex2->getMessage())
          )
      );


}
$db = null;
?>
</body></html>

In my attempts to debug this I've realized my error reporting is not WAI - if I change the database name, I get an error which is great (and expected). But if I change the table name - for example, to something made up that doesn't exist - I don't seem to get a PDOException, which I would have expected. Current theory is the database is connecting okay (it throws an error if it doesn't) but the table bit is broken and not throwing an error.

How can I make PDO fire an exception whenever it can't execute a statement?

Sam

Upvotes: 0

Views: 125

Answers (1)

Sammitch
Sammitch

Reputation: 32272

PDO will throw exceptions if it can't create the object because that's OOP code, but by default it fails silently for mySQL errors, instead passing false for the various function returns.

http://php.net/manual/en/pdo.error-handling.php

Change your code to set the relevant attribute:

$db = new pdo('mysql:unix_socket=/cloudsql/myidhere:cloudsql;dbname=mydb-schema', 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Upvotes: 1

Related Questions