Jump to content

Archived

This topic is now archived and is closed to further replies.

just-j

why does my foreach loop echo twice?

Recommended Posts

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.
[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"
?>
[/code]

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?

Share this post


Link to post
Share on other sites
SQL needs to be "SELECT genre, user FROM users"

Loop using while()
[code=php:0]
<?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"
?>
[/code]

Share this post


Link to post
Share on other sites
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:

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

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.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.