Jump to content


MySQL query and foreach loop not acting as wanted

  • Please log in to reply
2 replies to this topic

#1 TRobs

  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 03 March 2006 - 01:10 AM

First off, I would just like to say "hi" as this is my first post here.

Here is the code
$guild_info_query = mysql_query ("
                        SELECT *
                        FROM `guilds`
                        WHERE `name` = '$guild'
                        LIMIT 0,1") or die (mysql_error ());
$guild_info = mysql_fetch_array ($guild_info_query);

$guild_id = $guild_info['id'];

$member_info_query = mysql_query ("
                        SELECT `id`, `username`, `level`
                        FROM `users`
                        WHERE `guild`  = '$guild'
                        ORDER BY `username`") or die (mysql_error ());
$member_info = mysql_fetch_array ($member_info_query);
print_r ($member_info);

        <td>Guild Name:</td>
        <td><?php print $guild; ?></td>
        <td>Guild Leader:</td>
        <td><?php foreach ($member_info as $leader) { if ($leader['id'] == $guild_id) { print $leader['username']; } } ?></td>
        <td><?php print $guild_info['description']; ?></td>
        <td colspan="2">Members</td>
    foreach ($member_info as $member)
        print "<tr><td>   <a href=\"viewcharacter.php?view=".$member['id']."\">".$member['username']."</a></td><td>".$member['level']."</td></tr>";

The first problem I am having has to do with the second MySQL query. While testing I have 3 people in the guild. $guild is defined in an included file. When I run the query through phpMyAdmin it works the way i want it too, but in this file it returns only one of the guild members and it adds new things to the array from which im not sure where they come.
Here is what the print_r function returns:
Array ( [0] => 2 [id] => 2 [1] => Drew [username] => Drew [2] => 1 [level] => 1 )

My other Problem takes place in both of the foreach loops. In the first loop I want it to print the username of the person in the guild whose user_id == the guild_id. Instead it prints all the numbers in the array the equal the guild_id.

Second foreach loop should print the user name and their level, but instead it goes through each variable in the array and just prints the first letter or number and goes onto the next.

Thanks for the help in advanced. I am willing to try any alternatives to the foreach loops

#2 wickning1

  • Members
  • PipPipPip
  • Advanced Member
  • 405 posts

Posted 03 March 2006 - 01:25 AM

mysql_fetch_array() only returns one row at a time.

You have to use something like
while ($leader = mysql_fetch_array($member_info_query)) {
// do your output

to get all the rows.

#3 TRobs

  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 03 March 2006 - 03:12 AM

awsome, thanks for the help.

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users