php - 使用php从while循环语句中的不同表中获取值

标签 php mysql while-loop

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

$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,但仍然一无所获,我已经为此苦苦挣扎了两天。

最佳答案

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

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;

关于php - 使用php从while循环语句中的不同表中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55785120/

相关文章:

c - 如何使用 while 循环

mysql - aws 数据管道 s3 到 mysql 错误

mysql - SQLite "split"行分成多行

c - 在 C 中用 scanf 循环

php - 从不同数据库删除查询(删除有关 id 的所有信息)速度很慢

mysql - 在 mysql select 中设置不同的 lower 和 upper

php - 虽然循环不显示所有值

PHP 7 | chr() + strict_types === 错误?

php - Symfony2 - 安装了 FOS 用户包的自定义身份验证提供程序

php - 使用 PHP 获取 USPS 订单跟踪状态