如何使用 PHP 的 PDO 检查数据库查询返回的结果

2021-12-26 00:00:00 php pdo

如何在 PHP 中使用 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>';
}

我以前是这样做的:

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

但是刚刚开始使用 PDO 和准备好的语句并且检查 $STH 似乎没有按预期工作 - 它总是有价值的!

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

推荐答案

我会尝试使用 rowCount():

I would try to use rowCount():

$rows_found = $STH->rowCount();

但是,根据手册:

如果关联的 PDOStatement 执行的最后一条 SQL 语句是一条 SELECT 语句,某些数据库可能会返回行数该语句返回.但是,不能保证此行为适用于所有数据库,不应依赖于可移植应用程序.

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.

您当然也可以在 while 循环之前设置一个变量,在循环中更改它并检查循环后的值...

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

相关文章