簡體   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