2011-10-14 23 views
2

因爲mysql_num_rows返回false mysql_num_rows如果沒有行返回,那會是最好做:正確的方式來問,如果在PHP

$query = mysql_query("SELECT id FROM table WHERE something = 'this'"); 
$result = mysql_num_rows($query); 

if ($result) { } 

或者我應該做的:

if ($result >= 1) { } 
+1

......我愛大家怎麼也來了一樣簡單的解決方案的十幾種不同的方式。我想用PHP/MySQL永遠不會有明確的答案。 – Oseer

+0

請不要使用mysql來代替使用PDO或準備語句 –

回答

2

正確一個

$result = mysql_query("SELECT id FROM table WHERE something = 'this'"); 
if (mysql_num_rows($result)){ 
    //there are results 
} 
但是

,你可以這樣做更容易,而不檢查

$result = mysql_query("SELECT id FROM table WHERE something = 'this'"); 
while($row = mysql_fetch_assoc($result)) 
    //there are results 
} 

請。給變量指定專用名稱

+0

謝謝,我喜歡第一個例子。 – Oseer

+0

不利之處在於,如果沒有記錄存在,您無法顯示其他內容,這在許多情況下都是可取的。但如果不是,這是一個好習慣! – giorgio

1

如果沒有行返回,它不會返回false,如果發生錯誤,它將返回false。您可以處理這種方式:

if ($result === false) { 
    /* An error occurred - do something */ 
} else { 
    /* $result is set to some number >= 0 */ 
} 
0

我覺得誠實是

$query = mysql_query("SELECT id FROM table WHERE something = 'this'"); 
if (mysql_num_rows($query)!==FALSE){ 
    //there are results 
} 

是比較合適的。

5

正確的方法將使用PDO,而不是古老的mysql_*功能:

$stmt = $dbh->prepare('SELECT item_id FROM Items WHERE name = :param'); 
$stmt->bindParam(':param', $some_name, PDO::PARAM_STR, 127); 
if ($stmt->execute()) 
{ 
    echo $stmt->rowCount(); 
    var_dump($stmt->fetchAll(PDO::FETCH_ASSOC)); 
} 
+2

+1,mysql_ *是爲MySQL版本4和更舊版本編寫的。有時間刷新 – OptimusCrime

0

計數會返回一個值,你不能指望,然後調用mysql_num_rows。它是另一個。

你可以做

$isExist = mysql_query("Select count(id) from ..."); 
$r = mysql_fetch_array($isExist); 
if($r['COUNT(id)'] > 0){ 
//item exists 
}else{ 
//item doesnt exist 
} 

如果備選地爲可以執行查詢:

$isexist = mysql_query("select * from wcddl_filehosts where downloadid = '".$download[id]."'"); 
if(mysql_num_rows($isExists)>0){ 
//we have items 
}else{ 
//we dont have items 
}