首页 > 解决方案 > 使用php从while循环语句中的不同表中获取值

问题描述

我遇到了从两个不同的表中检索值的问题。这是到目前为止的代码:

$result = mysqli_query($conn,"SELECT * FROM articles");
$num = mysqli_num_rows($result);

while ($row = mysqli_fetch_array($result)) {
    $uid=$row['_uid'];

    $result2 = mysqli_query($conn, "SELECT _username FROM users WHERE _id = '$uid' ";
    $num2 = mysqli_num_rows($result2);

    while ($row2 = mysqli_fetch_array($result2)) {
        $username = $row2['_username'];
    }
    $divtext='<h3>'.$row['_posttype'].'</h3> <h2>'.$username.' </h2>';
}    

我一直在阅读我应该在一段时间内使用多个查询执行此操作,在 w3 上也发现您可以直接使用以下方法直接将值分配给变量:

"SELECT _username INTO $username FROM users WHERE  _id = '$uid'  LIMIT 1";    

但这在 myadmin 中的 SQL 中有效,在 php 中我找不到如何转换它。我还用 fetch_assoc 替换了 fetch_row 仍然没有,我已经为此苦苦挣扎了两天。

标签: phpmysqlwhile-loop

解决方案


您可以使用单个查询选择所有值

SELECT a._uid , a._posttype, u._username 
FROM articles a
INNER JOIN users u on a._uid = u._id 

..

$result = mysqli_query($conn,
  "SELECT a._uid , a._posttype, u._username 
  FROM articles a
  INNER JOIN users u on a._uid = u._id");
$num = mysqli_num_rows($result);

while ($row = mysqli_fetch_array($result)) {

    $divtext='<h3>'.$row['_posttype'].'</h3> <h2>'.$username.' </h2>';

}  

$echo $divtext;

推荐阅读