Jump to content

why does my foreach loop echo twice?


just-j

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?
Link to comment
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]
Link to comment
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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.