Johan Larsson
Johan Larsson

Reputation: 175

Loop works only if there is one row returned

I'm querying a db with this command:

$result = mysql_query("SELECT * FROM users WHERE country = '$_SESSION[country]' AND city = '$_SESSION[city]' ORDER BY id DESC");
if(mysql_num_rows($result) == 1) {
  while($row = mysql_fetch_array($result)) {
    echo "OK";
    $n = 1;
    echo '<div class="control-group">
          <div class="controls">
          <label class="checkbox">
          <input type="checkbox" name="users" value="'.$row['id'].'" onclick="\'chkcontrol('.$n++.')\';">'.$row['name'].'
          </label>
          </div>
          </div>';
  }
}

It returns True (works) if I have only one row in the table. If I add another one, it returns False. What am I missing?

Upvotes: 0

Views: 78

Answers (2)

Akash
Akash

Reputation: 5012

Your query with the session variables seems incorrect, it should be

$result = mysql_query("SELECT * FROM users WHERE country = '{$_SESSION['country']}' AND city = '{$_SESSION['city']}' ORDER BY id DESC");

Upvotes: 0

Johan Larsson
Johan Larsson

Reputation: 175

if(mysql_num_rows($result) == 1) has to be if(mysql_num_rows($result) >= 1) for sure.

Otherwise the if will only be true (and loop entered) when mysql_num_rows($result) is exactly 1.

Solved.

Upvotes: 2

Related Questions