我试图将另一个表中的列添加到来自另一个表的while循环中,我尝试了类似这样的东西,但似乎没有用。我怎样才能实现这样的目标?据我所知,我需要保存数组中data_auth的变量,但如何用循环回显它们呢?
$SQL = mysql_query("SELECT * FROM users ORDER BY data_reg DESC LIMIT $offset, $rowsperpage");
while($rand = mysql_fetch_assoc($SQL)){
$id = $rand['id'];
$user= $rand['user'];
$SQL2 = mysql_query("SELECT data_auth FROM access_log WHERE user = '$user'");
while($rand = mysql_fetch_assoc($SQL2)){
$data_auth = $rand['data_auth'];
}
?>
<li><?php echo "$user"; ?></li>
<li><?php echo "$data_auth"; ?></li>
<?php
}
?>
答案 0 :(得分:3)
您可以使用ONE sql查询,如下所示:
//$SQL = mysql_query("SELECT users.*,access_log.data_auth FROM users,access_log WHERE users.user = access_log.user ORDER BY data_reg DESC LIMIT $offset, $rowsperpage");
//SQL with JOIN syntax
$SQL = mysql_query("SELECT users.*,access_log.data_auth FROM users INNER JOIN access_log ON users.user = access_log.user ORDER BY data_reg DESC LIMIT $offset, $rowsperpage");
while($rand = mysql_fetch_assoc($SQL)){
$id = $rand['id'];
$user= $rand['user'];
$auth = $rand['data_auth'];
?>
<li><?php echo $user; ?></li>
<li><?php echo $auth; ?></li>
<?php
}
?>
答案 1 :(得分:2)
据我了解 - 您只想在与用户相关的列中显示所有data_auth值的列表。最简单的方法是:
$SQL = mysql_query("SELECT * FROM users ORDER BY data_reg DESC LIMIT $offset, $rowsperpage");
while($rand = mysql_fetch_assoc($SQL)){
$id = $rand['id'];
$user= $rand['user'];
$SQL2 = mysql_query("SELECT data_auth FROM access_log WHERE user = '$user'");
?>
<li><?php echo "$user"; ?></li>
<li><?php
while($rand2 = mysql_fetch_assoc($SQL2)){
echo $rand2['data_auth'] . '<br/>';
}
?>
</li>
<?php
}
?>
此外,在第二个while
中使用相同的变量名称是不安全的。
或者使用临时数组:
$SQL = mysql_query("SELECT * FROM users ORDER BY data_reg DESC LIMIT $offset, $rowsperpage");
while($rand = mysql_fetch_assoc($SQL)){
$id = $rand['id'];
$user= $rand['user'];
$SQL2 = mysql_query("SELECT data_auth FROM access_log WHERE user = '$user'");
$data_auth = array();
while($rand2 = mysql_fetch_assoc($SQL2)){
$data_auth[] = $rand2['data_auth'];
}
?>
<li><?php echo "$user"; ?></li>
<li><?php foreach($data_auth as $da){
echo $da . "<br/>";
}
?>
</li>
<?php
}
?>
答案 2 :(得分:0)
data_auth变量无法打印在另一个while循环中,而mysql没有获取它,因此你输错了:
<li><?php echo "data_auth"; ?></li>