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

How do I check db query returned results using PHP#39;s PDO(如何使用 PHP 的 PDO 检查数据库查询返回的结果)
本文介绍了如何使用 PHP 的 PDO 检查数据库查询返回的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

如何在 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...

这篇关于如何使用 PHP 的 PDO 检查数据库查询返回的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)