Amnestic
Amnestic

Reputation: 660

mysql_num_rows not working properly

I'm trying to check if the value of a mysql query returns false or actually contains a value. My first solution which worked properly looked like this:

    $gotTrailer = mysql_query("SELECT trailer FROM film_backup WHERE id='".key($countValues)."'");
    $iHasTrailer = mysql_fetch_array($gotTrailer);
    while(mysql_num_rows($gotTrailer)==''){
        next($countValues);
        $gotTrailer = mysql_query("SELECT trailer FROM film_backup WHERE id='".key($countValues)."'");
        $iHasTrailer = mysql_fetch_array($gotTrailer);
    }

This is a truly ugly solution, so I tried using mysql_num_rows() instead:

$gotTrailer = mysql_query("SELECT trailer FROM film_backup WHERE id='".key($countValues)."'");
    while(mysql_num_rows($gotTrailer)==0){
        next($countValues);
        $gotTrailer = mysql_query("SELECT trailer FROM film_backup WHERE id='".key($countValues)."'");
    }

But for whatever reason, this simply won't work. I tried using === false as well, but I geniunely don't know what's wrong. Hope you can help.

Upvotes: 0

Views: 2658

Answers (3)

Khawer Zeshan
Khawer Zeshan

Reputation: 9646

You can try with a For Loop as well

    $gotTrailer = mysql_query("SELECT trailer FROM film_backup WHERE id='".key($countValues)."'");

    for($i=0; $i<mysql_num_rows($gotTrailer); $i++)
    {
       next($countValues);
       $gotTrailer = mysql_query("SELECT trailer FROM film_backup WHERE id='".key($countValues)."'");
    }

Upvotes: 0

elvena
elvena

Reputation: 421

mysql_query returns false on error. If you want to check if there is an error on the query or not, you should check the return value of that function.

Now, if you want to check if there IS a result or not, mysql_num_rows will return >= 0 or false on error. So, your while should be

 while( (mysql_num_rows($gotTrailer) !== false) ){

Besides all this, the code has other flaws, next() could return false and the mysql_query will fail, also, remember to escape the queries to avoid SQL injection.

Upvotes: 0

BLaZuRE
BLaZuRE

Reputation: 2406

mysql_query() will return false only when it errors out. If the query returns an empty result, it still returns a resource (not false, empty, or 0).

mysql_fetch_array() will return false if there are no more rows, otherwise you are returned an array.

On a sidenote, these methods have been deprecated.

Resources: http://php.net/manual/en/function.mysql-query.php

http://www.php.net/manual/en/function.mysql-fetch-array.php

Upvotes: 1

Related Questions