简体   繁体   中英

How do I check db query returned results using PHP's PDO

How do I check if my result set is empty using PDO in PHP?

$SQL = "SELECT ......... ORDER BY lightboxName ASC;";
$STH = $DBH->prepare($SQL);
$STH->bindParam(':member_id', $member_id);
$STH->execute();
$STH->setFetchMode(PDO::FETCH_ASSOC);

while($row = $STH->fetch()) {
    $lightbox_name = $row['lightboxName'];
    $lightbox_id = $row['lightboxID'];
    echo '<option value="'.$lightbox_id.'">'.$lightbox_name.'</option>';
}

I used to do it like this:

$result = mysql_query("SELECT ...... ORDER BY lightboxName ASC;");
if(!$result) { echo 'No results found!'; }

But have just started using PDO and prepared statements and checking against $STH does not seem to work as expected — it always has value!

I would try to use rowCount() :

$rows_found = $STH->rowCount();

But, according to the manual:

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

If it does not work for you, you can use the other method mentioned in the manual.

You can of course also set a variable before your while loop, change it in your loop and check the value after the loop...

Just dump information about variable.

var_dump($STH)

EDIT

I just got the question. There is rowCount() function for that. Just use $STH->rowCount(); for the row count then compare it.

OK here is the code it does work and finally after a few hours of looking around and mix matching some answers here is one that will in fact return a count on your select statement. SQL is the select statement obviously $username1 is the post of the text box for username. $password1 is the same as the username setup. Other than that you should have everything you need to make it work simply substitute your variables in place of mine. I hope this saves some people time as I searched a while trying to get exactly what I wanted here. This solution is for when you have a select statement and you want to be able to continue or stop based on it returning something.

SQL = 'SELECT * from Users WHERE Username = :Username AND Password = :Password';
STH = $conn->prepare($SQL);
STH->bindParam(':Username', $username1);
STH->bindParam(':Password', $password1);
STH->execute();
STH->setFetchMode(PDO::FETCH_ASSOC);


row_count = $STH->rowCount();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM