我遇到了从两个不同的表中检索值的问题。到目前为止,这是代码:
$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_row替换了fetch_assoc,仍然一无所有,为此我已经挣扎了两天。
答案 0 :(得分:0)
您可以使用单个查询选择所有值
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;