Page 1 of 1

Foreach returns only partial results, While works...

Posted: Fri Jun 25, 2004 8:22 am
by tomfra
I need to select rows from database table "filenames" and then display them.

The below code works just fine:

Code: Select all

$query = "SELECT * FROM filenames";
  $result = mysql_query($query);
  
  while ($row = mysql_fetch_array($result)) {
    $orig_name = $row["orig_name"];
    $new_name = $row["new_name"];
  echo "$orig_name<br>";
  }
But this code behaves real strange:

Code: Select all

$query = "SELECT * FROM filenames";
  $result = mysql_query($query);
 
foreach(mysql_fetch_array($result) AS $key => $value){
  $row = mysql_fetch_array($result);
  $orig_name = $row["orig_name"];
  $new_name = $row["new_name"];
   echo "$orig_name<br>";
  }
There are currently 20 rows and the first code which uses "while" does display all of them properly. The second piece of code which uses "foreach" does display only 8 rows starting with the second one.

Any ideas what the problem could be? Of course I can simply use the code that works but I would like to know why the other code behaves so odd.

Thanks!

Tomas

Posted: Fri Jun 25, 2004 9:50 am
by pickle
When you call mysql_fetch_array($result) in the foreach loop, that is retrieving a row from the result and putting it into $key and $value (which won't work since the output from mysql_fetch_array($result) is an array, not an array element). Then, when you call mysql_fetch_array($result) inside the foreach loop, you're retrieving yet another row. So, for each loop you do, you are retrieving two rows.

I'd stick with the while loop - the foreach loop is for looping through arrays more than for looping through MySQL results.

Posted: Fri Jun 25, 2004 11:22 am
by tomfra
Thanks for the reply!

But then the question is how do I solve the problem I described here: viewtopic.php?t=23100 without the use of "foreach". Before, I used a simple array but then decided everything will work better with a MySQL database so that's why I have this problem.

As always, any help is welcome.

Thanks again,

Tomas

Posted: Fri Jun 25, 2004 11:39 am
by pickle
How about a combination of the loops:

Code: Select all

$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
   foreach($row as $key => $value)
   {
      ${new_value.$key} = $value;
    }
}