PDO错误处理查询

I recently switched from using MySQLI to using PDO and it seems like PDO doesn't always let you know when there is an error when you run a query that errors.

With MYSQLI, you could do:

if($dbh->query("SELECT ...") === false) {
  echo "Error";
}

If there was an SQL syntax error or an improperly named column or whatnot, this would always happen (which is the desired result).

With PDO, when you do:

if($dbh->query("SELECT ...") === false) {
  echo "Error";
}

This does not always happen when you have the same sort of aforementioned errors!

So how do I get the same desired effect with PDO? I want to be able to have the case in the above piece of code happen ANYTIME there is an issue with the query. In other words, unless I get some sort of result set back (be it no records or some number of records), I want $dbh->query(...) to return false.

Try enabling exceptions:

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

Then catch them:

try{
  $dbh->query("SELECT ...");

}catch(\Exception $e){
  printf('Error: %s', $e->getMessage());  
}

First of all, your idea of error reporting with mysqli was wrong. Echoing error out is a very bad practice. Instead, you had to translate mysqli error into PHP error.

So you have to do with PDO.
Luckily, PDO can throw exceptions. Connecting the way explained in the PDO tag wiki you will always have an exception, which, when not caught, will be translated into PHP error as well, and can be handled exactly the same way as other PHP errors.

As a side effect, you won't have to check query results at all, creating long and windy structures with all the query, it's execution and error checking stuffed in one line. So, you can write neat and readable code:

$sql = "SELECT ...";
$dbh->query($sql);

note that if you are using query() instead of prepare() there is no point in using PDO at all.