Question

When testing my try-catch block with database->Select I was expecting the exception to be caught when trying to echo a PDOstatement but instead it tells me the error is not caught.

Catchable fatal error: Object of class PDOStatement could not be converted to string

I don't understand what I'm doing wrong here.

Here is the code:

class database{

  private $conn;
  private $sqlError;

   public function __construct() {
      $server = "localhost";
      $username = "user";
      $pass = "password";
      $database = 'dbname';
      $dsn = sprintf('mysql:dbname=%s;host=%s', $database, $server);
      try {
          $this->conn = new PDO($dsn, $username, $pass);
      } catch (Exception $exc) {
          $this->sqlError = 'SQL Error: ' . $exc->getCode();
      }
  }

    public function Select($query, $values=array()) {
      unset($this->sqlError);
      try {
          $qry = $this->conn->prepare('select ' . $query);
          echo $qry;    //invalid operation, I expect exception to be thrown
          $qry->execute($values);
          $result = $qry->fetchAll(PDO::FETCH_OBJ);
          $error = $qry->errorInfo();
          if ($error[1]) {
              $this->sqlError = 'SQL Error: ' . $error[1];
          }
          return $result;
      } catch (Exception $exc) {
          $this->sqlError = 'SQL Error: ' . $exc->getCode();
      }
    }


}
Was it helpful?

Solution

A Catchable Fatal Error is not an Exception, it is an Error. It cannot be caught by a try/catch block, but by a custom error handler. See this answer for more info.

This line:

echo $qry;    //invalid operation, I expect exception to be thrown

You are correct that it is invalid, but incorrect that an Exception is thrown. Unless an object has a valid __toString() method defined, which PDOStatement does not, attempting to cast as a string will generate a PHP error, not an Exception. This is because the code attempting to cast the object to a string is part of the PHP core, and not some bit in a class somewhere.

If you want to look at the query contained in a PDOStatement object you need to access the read-only property $stmt->queryString.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top