0

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();
      }
    }


}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The echo $qry was a deliberate attempt to throw an exception, but I now understand the difference from your nice explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.