0

I have sql statement that adds results into the variable But when I put that variable($team) in my second sql statement it doesn't work WHERE id = '$team'. How would I go about this?

$query = mysql_query("SELECT team_name FROM team");
$team = array();
while($row = mysql_fetch_assoc($query)){
$team[] = $row;}
echo $arra[0];
$loop=count($team);
for($x=0;$x<$loop;$x++)
foreach($team[$x] as $child) {



$result = mysql_query("SELECT * FROM members 
WHERE id =  '$team'") 
or die(mysql_error());  
while($row = mysql_fetch_array( $result )) {
echo '<td>' . $row['first_name'] . '</td>'; 
} 
4
  • Shouldn't it be $child instead of $team in your foreach loop? Commented Sep 29, 2013 at 23:32
  • 1
    Unless it's a typo, echo $arra[0]; may need to be echo $array[0]; if you have a variable called $array, or echo array[0]; or echo $team[0]; --- either way, echo $arra[0]; doesn't look right. Commented Sep 29, 2013 at 23:37
  • 1
    You should not be using mysql_* functions in new code, as it is deprecated and will be removed in the future. Commented Sep 29, 2013 at 23:38
  • 1
    Recommend using php's PDO!!! Commented Sep 29, 2013 at 23:40

3 Answers 3

3

use join php function if the $team is an array like:

$team = join(',', $team);
$result = mysql_query("SELECT * FROM members WHERE id in ($team)") or die(mysql_error());  
Sign up to request clarification or add additional context in comments.

Comments

2

I agree with jetawe's use of join, but I recommend a different type of join.

SELECT m.first_name
FROM team AS t
LEFT OUTER JOIN members AS m ON m.id=t.team_name;

PS. Be sure to use a surrogate key for table "team" and not use the name.

2 Comments

When I echo "$team" I get an ID printed on the page. Why cant I just put "$team" in my sql statement like this : WHERE id = '$team'")
@user2055697. You can. Just make sure your SQL is what you think it is. Team sure be an integer data type, and if it isn't, you might need quotes around it (however, still change your database schema to make it an integer).
1

I think your question is unclear and your code is a little bit messy.

$query = mysql_query("SELECT team_name FROM team");
// loop through each team
while($team = mysql_fetch_assoc($query)){
    // find members for this team
    $query = mysql_query("SELECT * FROM members WHERE id = '" . $team['team_name'] . "'") or die(mysql_error());
    while ($member = mysql_fetch_array($query)) {
        echo '<td>' . $member['first_name'] . '</td>'; 
    }
}

Though, the best way is to use joins like user1032531 has shown instead of making several calls to the database.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.