繁体   English   中英

在MySQL中使用PHP时和if语句

[英]While and if statement in php with mysql

我已经被这个问题困扰了一段时间了。 我相信答案很容易就能在Google上找到,但我一直找不到要搜索的单词,所以我的最后选择就是在这里。 提前致谢!

我有这个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”。

再次再次感谢您的所有帮助!

您需要做的只是以下几点:

$query = "SELECT `status` FROM `table` WHERE `status` = 'Opened'";
$result = mysqli_query($conn, $query);
$test = (mysqli_num_rows($result) > 0) ? 1 : 0;

无需提取,它也会更快。

最好直接从数据库中选择所需的数据,而不是使用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;
}

暂无
暂无

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

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