因为mysql_num_rows如果没有返回任何行返回false,那么最好这样做:
$query = mysql_query("SELECT id FROM table WHERE something = 'this'");
$result = mysql_num_rows($query);
if ($result) { }
或者我应该这样做:
if ($result >= 1) { }
正确的方法是使用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 ));
}
正确的
$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
}
请。给变量起一个合适的名字
如果没有返回行,则不返回false
,在错误的情况下返回false
。你可以这样处理:
if ($result === false) {
/* An error occurred - do something */
} else {
/* $result is set to some number >= 0 */
}
说实话
$query = mysql_query("SELECT id FROM table WHERE something = 'this'");
if (mysql_num_rows($query)!==FALSE){
//there are results
}
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
}