I've created a query in SQL to return all Sport teams for a specific users.

$get_sport = mysql_query("SELECT sport_name FROM sport, user_sport WHERE sport.sportID=user_sport.sportID") or die(mysql_error());

$get_sport_val = mysql_fetch_array($get_sport);

The relationship between user and sport is a one-to-many relationship, i.e. one user can have many sports.

When I execute this code:

echo $get_sport_val[0];

It's fine, it returns the first sport that is associated with the user. But when I enter this code:

echo $get_sport_val[1];

I get the error:

Notice: Undefined offset: 1 in C:\Test\sport_test.php on line 62

Line 62 refers to the array index '1'.

Below is an example of how the tables would look. As you can see, searching for the Sport_ID will return three different sports.

Table: Sport
Sport_ID Sport_name
1 --------(sport1)
2 --------(sport2)
3 --------(sport3)

Table: User_sport
User_ID Sport_ID
1 ------ 1
1 ------ 2
1 ------ 3

What I want to do is iterate through the list of sports in the result array and print (or echo) them to the screen.

Thank you for your help. 🙂

    You say that's what the array result should look, but how does it actually look?

    Use [man]print_r/man to look at $get_sport_val and I think you'll only see one result set.

    You need to use a while or foreach loop to iterate through the result and add it to the $get_sport_val array.

      I've tried the print_r() command as you said, and yes it worked. But having said that so did the echo command.

      I created a foreach() loop to get the values in the array, but I suspect my code is wrong somewhere as it only returns the first value in the array. Here's my code:

      foreach ($get_sport_val as $val) {
      
      ?>            
      Sport Name: <?php echo $val; ?> <br /> <?

      Thank you, I hope you can see where I'm going wrong, because I can't :glare:

        $get_sport = mysql_query("SELECT sport_name FROM sport, user_sport WHERE sport.sportID=user_sport.sportID") or die(mysql_error());
        while($row = mysql_fetch_assoc($get_sport))
        {
          $get_sport_val[] = $row['sport_name'];
        }
        

          Cheers Rrincewind456 and NogDog, the problem is now resolved.

          I used both your suggestions and finally came to a successful conclusion. 🙂

            Write a Reply...