正确的方法来询问PHP中的mysql_num_rows

时间:2011-10-14 12:36:38

标签: php mysql mysql-num-rows

因为如果没有返回任何行,mysql_num_rows会返回false,那么最好是这样做:

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

if ($result) { }

或者我应该这样做:

if ($result >= 1) { }

5 个答案:

答案 0 :(得分: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 ));
}

答案 1 :(得分: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
}

请。为变量指定专有名称

答案 2 :(得分:1)

如果没有返回任何行,则不会返回false,如果出现错误,则返回false。你可以这样处理:

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

答案 3 :(得分:0)

我诚实地认为

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

更合适。

答案 4 :(得分:0)

Count将返回一个值,您无法计数然后调用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
}