gpt4 book ai didi

php - PDO 获取结果或 while 循环中的 bool 值

转载 作者:行者123 更新时间:2023-11-29 06:25:10 24 4
gpt4 key购买 nike

如果数据库中没有记录,我试图输出一个带有 nil 值的 HTML 表单。但是,如果有记录(可能有多组数据),我想将表单中的值默认为记录中已有的值。

所以我有一个 PDO 查询和提取设置如下:

$con = new PDO(...);
$con->setAttribute(...);
$query = "SELECT DISTINCT data FROM ...";
$stmt = $con->prepare($query);
$stmt->execute();
$first_loop = true; //print 1 form if data set is empty
while ($first_loop || $obj = $stmt->fetch()) {
//process $obj and print form
$first_loop = false;
}

上面代码的问题是$stmt->fetch()在处理完一组数据后没有指向下一行。如果我从 while 语句中删除 $first_loop 那么一切正常,前提是我的记录中至少有一组数据。因为如果没有,我的整个表格都不会打印出来。

我不确定上述方法是否是实现我的目标的最佳方法,但如果是,我想听听我如何改进我的代码以解决该错误。

谢谢!

最佳答案

您可以检查行数,如果它大于零,则表示数据库包含值。
使用 num_rows

$stmt = $con->prepare($query);$stmt->execute();$stmt->store_result();if($stmt->num_rows>0) {  // database contains values    while ($obj = $stmt->fetch()) {        //process $obj and print form    }}else{  // form must have null values because no data found on database}

关于php - PDO 获取结果或 while 循环中的 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31491267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com