gpt4 book ai didi

php - php 和 mysql 中的 while 和 if 语句

转载 作者:行者123 更新时间:2023-11-29 04:36:21 25 4
gpt4 key购买 nike

我有这个 php 代码:

if(mysqli_num_rows($query) > 0) {
while($row = mysqli_fetch_array($query)) {
if ($row['status'] == "Opened") {
$test = "1";
} else {
$test = "0";
}
}
}
echo $test;

当数据库中有多个条目并且其中一个条目的状态不是“已打开”时,就会出现问题,因此 $test 返回“0”。我正在尝试实现,如果任何条目的状态为“已打开”,$test 将返回“1”。

最佳答案

最好直接从数据库中选择你需要的数据,而不是用 PHP 过滤掉它。

SELECT id, message, etc FROM tickets WHERE status = 'Opened'
// if it fetches data, you have open tickets and have directly access to the data of the open tickets.

SELECT count(*) AS total FROM tickets WHERE status = 'Opened'
// the result of this is a number of the total amount of opened tickets, perhaps better for this specific use.

但是关于如何修复循环的主题,您可以执行以下操作:

$open = false;

while($row = mysqli_fetch_array($query)) {
if ($row['status'] == "Opened") {
$open = true;
break;
}
}

因为这将退出 while 循环,设置 $open 以供进一步使用:

if($open){
// do your stuff;
}

关于php - php 和 mysql 中的 while 和 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40442368/

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