Proper way to ask if mysql_num_rows in PHP

Oseer picture Oseer · Oct 14, 2011 · Viewed 20.3k times · Source

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) { }

Answer

tereško picture tereško · Oct 14, 2011

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