php - 使用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 仍然没有,我已经为此苦苦挣扎了两天。
解决方案
您可以使用单个查询选择所有值
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;
推荐阅读
- google-apps-script - 将收音机的输入值作为参数传递给 google.script.run.withSuccessHandler
- php - API json邮递员和drupal 8
- java - 如何使用白盒为按钮编写单元测试?
- java - Apache Commons Math 中 DBSCAN 的自定义距离度量(v3.1 与 v3.6)
- angular - RXJS:返回外部 observable 的操作值
- unit-testing - 如何在库项目中测试 Yii2 模型?
- java - 错误:使用 Forge 启动 Minecraft 1.12.2 时无法找到或加载主类 net.minecraft.launchwrapper.Launch
- c# - asp.net核心中的部分标签助手和HTML助手有什么区别?
- r - 将数据加载到 Rstudio
- java - 如何用 0 在 1 的位置反转一个数字?