2

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) { }
Oseer
  • 740
  • 7
  • 19
  • 28
  • 1
    ... I love how everyone has a dozen different ways of coming up with the same simple solution. I guess there is never a clear-cut answer with PHP/MySQL. – Oseer Oct 14 '11 at 12:43
  • please dont use mysql instead use PDO or prepare statement – kim de castro Sep 21 '16 at 06:32

5 Answers5

5

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 ));
}
tereško
  • 58,060
  • 25
  • 98
  • 150
3

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

genesis
  • 50,477
  • 20
  • 96
  • 125
  • Thanks, I like that first example. – Oseer Oct 14 '11 at 12:44
  • downside to the second one is that you are not able to display something else in case no records are present, which is desirable in numerous of cases. But if it isn't, it is a good practice! – giorgio Oct 14 '11 at 12:45
1

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 */
 }
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
0

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

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.

fyr
  • 20,227
  • 7
  • 37
  • 53