Proper way to ask if mysql_num_rows in PHP

2019-04-02 06:26发布

问题:

Because mysql_num_rows returns false if there are no rows returned, would it be best to do:

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

if ($result) { }

Or should I do:

if ($result >= 1) { }

回答1:

The proper one

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

however, you could do this easier, without checking

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

Please. Give your variables proper names



回答2:

The proper way would be using PDO instead of the ancient mysql_* functions:

$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 ));
}


回答3:

It doesn't return false if no rows are returned, it returns false in the case of an error. You can handle that this way:

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


回答4:

I think honestly that

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

is more appropriate.



回答5:

Count will return a value, and you cannot count and then call mysql_num_rows. It is either one of the other.

You could do

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

If alternatively you can do the query as:

$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
}