1

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 http://img249.imageshack.us/img249/70/endlessloop.png

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

$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
   }

2 Comments

But then I have to do two mysql_fetch_array($query) if I want to make a check for empty request?
@Neb if you want to check for an empty result, use if (mysql_num_rows($query) == 0)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.