简体   繁体   English

在MySQL中使用PHP时和if语句

[英]While and if statement in php with mysql

I have been stuck with this problem for awhile now. 我已经被这个问题困扰了一段时间了。 I'm sure the answer is on easily find able on Google but I have been unable to find the words to search so my last resort is here. 我相信答案很容易就能在Google上找到,但我一直找不到要搜索的单词,所以我的最后选择就是在这里。 Thanks in advanced! 提前致谢!

I have this php code: 我有这个PHP代码:

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

The problem occurs when there are multiple entries in the database and one of those entries does not have status = "Opened" therefore $test returns "0". 当数据库中有多个条目并且其中一个条目的状态不为“打开”时,就会发生问题,因此$ test返回“ 0”。 What I am trying to accomplish is if ANY of the entries have status = "Opened", $test will return "1". 我要完成的工作是,如果任何一项的状态为“打开”,$ test将返回“ 1”。

Once again thanks in advance for all your help! 再次再次感谢您的所有帮助!

All you need to do is the following: 您需要做的只是以下几点:

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

No need to fetch, it will be faster too. 无需提取,它也会更快。

It might be better to directly select the data you need from the database instead of filtering it out with PHP. 最好直接从数据库中选择所需的数据,而不是使用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.

But on the subject on how to fix your loop you can do the following: 但是关于如何修复循环的主题,您可以执行以下操作:

$open = false;

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

As this will quit the while loop, setting $open for futher use: 因为这将退出while循环,所以将$open设置为进一步使用:

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

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

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