我有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>';
}
答案 0 :(得分:3)
如果$ team是一个数组,则使用join php
函数:
$team = join(',', $team);
$result = mysql_query("SELECT * FROM members WHERE id in ($team)") or die(mysql_error());
答案 1 :(得分: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。请务必使用表“团队”的代理键,而不要使用名称。
答案 2 :(得分: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之类的联接,而不是多次调用数据库。