2016-11-05 78 views
1

我一直堅持這個問題一段時間了。我確信答案很容易在Google上找到,但我一直無法找到要搜索的詞,所以我最後的手段就在這裏。先謝謝了!雖然和if語句在MySQL與MySQL

我有這樣的PHP代碼:

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

當有數據庫中的多個條目和這些條目的一個沒有狀態=「打開」,因此$測試返回「0」出現問題。我試圖完成的是,如果任何條目的狀態=「已打開」,則$ test將返回「1」。

再次感謝您的幫助!

+0

你不應該用php中的循環來做這件事。您應該使用數據庫中的單個查詢來完成此操作。 –

+0

我會研究一下,謝謝! – user3724476

+0

這將取決於查詢是爲了什麼,你沒有發佈。 –

回答

2

從數據庫中直接選擇需要的數據可能會更好,而不是用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; 
} 
+0

謝謝!這對我有效。 – user3724476

2

所有你需要做的是以下幾點:

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

無需取出,它會更快了。

+0

經過測試,它只返回值「0」。 – user3724476

+0

仔細檢查您的餐桌,因爲此代碼正確 – meda