简体   繁体   English

PDO提取结果或在while循环中使用布尔值

[英]PDO fetch results OR boolean in while loop

I'm trying to output a HTML form with nil values if there are no records in the database. 如果数据库中没有记录,我试图输出具有nil值的HTML表单。 However, if there are records (there could be multiple sets of data), I want to default the values in the form to what's already in the records. 但是,如果有记录(可能有多组数据),我想将表单中的值默认为记录中已经存在的值。

So I have a PDO query and fetch set up as follows: 因此,我有一个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;
}

The issue with the above code is that $stmt->fetch() does not point to the next row after processing one set of data. 上面的代码的问题在于,在处理一组数据之后, $stmt->fetch()不会指向下一行。 If I remove $first_loop from the while statement then everything works fine, only if there is at least one set of data in my records. 如果我从while语句中删除$first_loop ,则一切正常,只有在我的记录中至少有一组数据时才可以。 Because if there isn't, my entire form doesn't get printed. 因为如果没有,则不会打印我的整个表格。

I'm not sure if the above method is the best to achieve my objective, but if it is, I'd like to hear how I can improve my code to solve the bug. 我不确定上述方法是否是实现我的目标的最佳方法,但是如果是,我想听听我如何改进代码以解决该错误。

Thanks! 谢谢!

You can check for no of rows, and if its greater than zero, it means database contains values. 您可以检查行数,如果行数大于零,则表示数据库包含值。
Use num_rows 使用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

}

You can't check your condition in while loop.Instead you can use if and isset to check your condition 您不能在while循环中检查条件,而是可以使用ifisset来检查条件

$first_loop = true; //print 1 form if data set is empty. 

    if(isset($first_loop))
    while ($obj = $stmt->fetch()) {
        //process $obj and print form
        $first_loop = false;
    }
    }else{
    $first_loop = false;
    }

 $servername = "localhost"; $username = "user"; $password = "pass"; $dbname = "test"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT DISTINCT data FROM ..."; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo $row["data"]."<br>"; } } else { echo nil; } $conn->close(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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