检查是否在PDO中执行了SQL查询[重复]

This question already has an answer here:

in mysql_query we can check if the query was executed or not by doing this:

$query = $yourdbconnection->fetch_array(mysql_query("SELECT * FROM tbl_name"));
if ($query){ // query is working }
else { // query is not working }

in PDO, I am doing something like this:

$query = $yourdbconnection->query("SELECT * FROM tbl_name");
$fetchquery = $query->fetchAll();
if ($fetchquery) { // query is working}
else { // query not working}

Is my code effective? what exactly the if statement doing? Is it doing the same thing that mysql_query was doing? How can I check if the query is returning 0 rows or not?

[EDIT]

I have found those solutions as a workaround to the problem

  1. using $stmt->fetch()

    prepare($sql); $stmt->execute();
    if ($data = $stmt->fetch()) {
        do {
            echo $data['model'] . '<br>';
        } while ($data = $stmt->fetch());
    } else {
        echo 'Empty Query';}
    
    ?>
  2. adding another query to count the number of rows see this answer

However, I am still looking for better solutions

</div>

To see if your query was executed, I would suggest setting your PDO in exception mode like Your Common Sense suggested. You can do it like this:

$dbh = new PDO('mysql:host=localhost;dbname=db', 'user', 'pass');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Concerning the best way to check if a query returned values or not in PDO, I suggest just doing a SELECT COUNT(*) FROM table query, like this:

<?php
$query = $dbh->query('SELECT COUNT(*) FROM table');
if ($query->fetchColumn() != 0) {
    /* Query has result(s) */
    $query = $dbh->query('SELECT * FROM table');
    /* ... */
} else {
    /* Query has no results */
}
?>

Let me know if you have any other questions.

there are 2 questions in your post.

1) what is the best way to check if the query returned values or not in PDO?

check returned values

2) how to check if SQL query was excuted in PDO

set PDO in exception mode as described in the tag wiki

By the way, for the "SELECT * FROM tbl_name" query you may wish to use fetchAll() instead of fetch().