0

我有将结果添加到变量中的 sql 语句但是当我将该变量($team)放在我的第二个 sql 语句中时它不起作用 WHERE id = '$team'。我该怎么办?

$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

3 回答 3

3

join php如果 $team 是一个数组,则使用函数,例如:

$team = join(',', $team);
$result = mysql_query("SELECT * FROM members WHERE id in ($team)") or die(mysql_error());  
于 2013-09-29T23:32:58.437 回答
2

我同意 jetawe 使用 join,但我建议使用不同类型的 join。

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

PS。请务必使用表“团队”的代理键,而不是使用名称。

于 2013-09-29T23:39:25.170 回答
1

我认为你的问题不清楚,你的代码有点乱。

$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>'; 
    }
}

不过,最好的方法是使用user1032531所示的连接,而不是多次调用数据库。

于 2013-09-29T23:49:11.497 回答