0

我正在尝试将另一个表中的列添加到另一个表中的 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  
      }
      ?>
4

3 回答 3

3

您可以只使用一个 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  
 }
 ?>
于 2012-10-01T22:03:44.783 回答
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  
      }
      ?>
于 2012-10-01T22:04:15.130 回答
0

data_auth 变量无法在 mysql 未获取的另一个 while 循环中打印,因此您有一个错字:

 <li><?php echo "data_auth"; ?></li>
于 2012-10-01T21:59:26.173 回答