Jump to content


Photo

why does my foreach loop echo twice?


  • Please log in to reply
2 replies to this topic

#1 just-j

just-j
  • Members
  • PipPipPip
  • Advanced Member
  • 52 posts

Posted 18 July 2006 - 08:12 PM

i have a foreach loop to display the users in the table..  i only have one person signed up, me, so i dont know if it echoes each user twice or just the first user  or the last user..  here is my code.
<?php
//  connect PHP to MySQL
mysql_connect ($Server, $Username, $Pass) or die ("Connection Denied");
mysql_select_db("tbbc") or die ("Unavaliable DB");
$result = mysql_query("SELECT user FROM users");
$users = mysql_fetch_array( $result );
$i = 0;
foreach ($users as $uza) {
$results = mysql_query("SELECT genre FROM users WHERE user='$uza'");
$goc = mysql_result($results, 0 );
   echo "$uza Genre of choice: $goc<br />";
   $i++;
}
echo "$i users signed up"
?>

the last echo also displays 2 users.  there isnt 2 of the same users in the table, just 1..  i know this is a simple fix.. can someone help me out please?

#2 willfitch

willfitch
  • Members
  • PipPipPip
  • Advanced Member
  • 109 posts
  • LocationNew Hope, PA

Posted 18 July 2006 - 08:18 PM

SQL needs to be "SELECT genre, user FROM users"

Loop using while()
<?php
//  connect PHP to MySQL
mysql_connect ($Server, $Username, $Pass) or die ("Connection Denied");
mysql_select_db("tbbc") or die ("Unavaliable DB");
$result = mysql_query("SELECT user FROM users");
$i=0;
while ($row = mysql_fetch_object($result)) {
   echo $row->user.' Genre of choice: '.$row->genre.'<br />';
   $i++;
}
echo "$i users signed up"
?>

Zend Certified Engineer (ZEND001989)
www.willfitch.com

#3 akitchin

akitchin
  • Staff Alumni
  • Advanced Member
  • 2,516 posts
  • LocationCalgary, AB, Canada

Posted 18 July 2006 - 08:25 PM

willfitch is right, you should do this with one query.

for the record though, the reason you were getting a double echo was because mysql_fetch_array() fetches the current row with both numerical and index keys.  that is, your $users array looked like:

$users[0] = 'username';
$users['user'] = 'username';

by specifying the second flag for mysql_fetch_array() (see the manual for the flag values) or using mysql_fetch_assoc(), you can narrow your array down to using either numerical or index keys.  however, i would suggest using a while() loop like will suggests.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users