2012-11-29 104 views
1

我存儲投票的數值範圍從0到10的數據庫。我遇到的問題是當符合查詢條件的投票是0它會觸發else語句。如果我將if語句更改爲...區分變量等於0和變量等於空陣列['列']

if ($vote >= 0) 

...然後,即使沒有滿足查詢條件的if語句總是爲true。我如何區分兩者?謝謝。

$data = array($page_id, $user_id, 'yes'); 
$STH3 = $DBH->prepare("SELECT vote from votes WHERE page_id = ? and user_id = ? and current = ?"); 
$STH3->execute($data); 
$STH3->setFetchMode(PDO::FETCH_ASSOC); 
$row = $STH3->fetch(); 
$vote = $row['vote']; 

if ($vote) { 
// some code 
} 

else { 
// some code 
} 

回答

1

鬆散的比較中,NULL將等於零。因此,如果沒有滿足您的條件且$row['vote']未填充且您將其不存在的值分配給$vote,則該值將變爲NULL。在將$vote設置爲空值之前,應該測試該值,以避免undefined index通知。然後檢查if()條件中的整數值$vote

// $vote is NULL if $row is not populated 
$vote = isset($row['vote']) ? $row['vote'] : NULL; 

// Check that $vote is an int value as opposed to NULL 
if (is_int($vote) && $vote >= 0) { 
    // Code executed when $vote is an integer value 
} 
else { 
    // Other code to execute if $row was empty 
} 

你也可以檢查是否$row是一個數組,這意味着你的fetch()呼叫出品行:

if (is_array($row)) { 
    // Code using $vote 
} 
else { 
    // No row was returned 
} 
+1

我用選項2的偉大工程。謝謝。 – arrogantprick