Dan
Dan

Reputation: 1011

php + mysql_num_rows issue?

I have a simple sql statement and I would like to perform a different action depending on the number of rows returned.

$result_lists = mysql_num_rows(mysql_query("SELECT * FROM db_table"));
    //To see the number returned
    print_r($result_lists);

    switch($result_lists) {
         case($result_lists == 0):
         //To prove which option is actually happening 
         print_r('lists==0: '.$result_lists);  
         break;

         case($result_lists > 1):
         //To prove which option is actually happening 
         print_r('lists>1: '.$result_lists);
         break;

         case($result_lists == 1):
         //To prove which option is actually happening 
         print_r('lists==1: '.$result_lists);  
         break;
    }

If 1 or more row is found, then the correct case is used, however, if zero rows are returned, for some reason the (> 1) case is carried out.

Can anyone see what might be going wrong?

Any advice appreciated.

Thanks.

Upvotes: 0

Views: 110

Answers (3)

Clement Herreman
Clement Herreman

Reputation: 10536

You shouldn't use switch like that.

switch($var)
{
    case 1:
        //Some stuff
        break;
    case 2:
        //Some stuff
        break;
    default:
        break;
}

It is the right way to do this. Use ifs and elses to do it, and yadayda ! Your bug will disappear.

Why ? Because case isn't made to evaluate statements. It only compare what's in the switch with what's in the case.

Upvotes: 1

Greg
Greg

Reputation: 321638

You're abusing the switch statement - you should replace it with ifs or change it like this:

switch ($result_lists)
{
     case 0:
         //To prove which option is actually happening 
         print_r('lists==0: '.$result_lists);  
         break;

     case 1:
         //To prove which option is actually happening 
         print_r('lists==1: '.$result_lists);  
         break;

     default:
         //To prove which option is actually happening 
         print_r('lists>1: '.$result_lists);
         break;
}

What you're doing at the moment is like this:

case($result_lists == 0):

// is like doing
if ($result_lists == ($result_lists == 0))

// which when $result_lists = 0 is the same as

if ($result_lists == true)
if (0 == 1)
// therefore false so it drops through to the next statement

case($result_lists > 1)
// the same as
if ($result_lists == ($result_lists > 1))
// when $result_lists = 0:
if ($result_lists == false)
if (0 == 0)

Upvotes: 8

lfx
lfx

Reputation: 1391

Returns zero or null, you have check

case($result_lists == 0 or null):

or maybe

 case(empty($result_lists)):

Upvotes: -4

Related Questions