tags:

views:

113

answers:

2

Hi, I have a problem with my php/mysql script. It should only output the while loop once but I am getting unlimited loops and an endless page.

$query = mysql_query("SELECT * FROM users WHERE username ='".base64_encode($_SESSION['username'])."' LIMIT 1"); 
$result = mysql_fetch_array($query);
   if(empty($result)){
      echo "No user... Error";
   }else{
   while($row = $result){
   ?>
<a href="index.php?user=<?=$row['id']?>"><?=base64_decode($row['username'])?></a> | <a  href="javascript:void(0);" id="logout">Logout</a>
   <?php
   }
}

I have tried a similar script with these same lines and it works perfectly

  $result = mysql_fetch_array($query);
   if(empty($result)){
      echo "No user... Error";
   }else{
   while($row = $result){
      //Something
   }
}

loop

+2  A: 

Look at:

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

It has in the example:

$result = mysql_query("SELECT id, name FROM mytable");

while ($row = mysql_fetch_array($result)) {
    printf("ID: %s  Name: %s", $row[0], $row[1]);  
}

mysql_fetch_array gets an array of the next row OR false if there is none left.

$row = $result will create a infinite loop when $result is anything that doesn't cast to false

ADDITIONALLY

you can use mysql_num_rows [ http://php.net/manual/en/function.mysql-num-rows.php ] to check to see if zero results were returned:

$result = mysql_query("SELECT id, name FROM mytable");

if(mysql_num_rows($result) {
    while ($row = mysql_fetch_array($result)) {
        printf("ID: %s  Name: %s", $row[0], $row[1]);  
    }
} else {
    // NO ROWS RETURNED
}
Bob Fincheimer
Thanks, 2nd example accepted
Neb
A: 

$row = $result is not a comparison but an assignment, and will always be true.

You need to put mysql_fetch_array into your while loop.

while($row = mysql_fetch_array($query)){
   ?>
<a href="index.php?user=<?=$row['id']?>"><?=base64_decode($row['username'])?></a> | <a  href="javascript:void(0);" id="logout">Logout</a>
   <?php
   }
Pekka
But then I have to do two mysql_fetch_array($query) if I want to make a check for empty request?
Neb
@Neb if you want to check for an empty result, use `if (mysql_num_rows($query) == 0)`
Pekka