【问题标题】:Get values from different tables inside a while loop statement using php使用php从while循环语句中的不同表中获取值
【发布时间】:2019-09-11 02:22:00
【问题描述】:

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

$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 仍然没有,我已经为此苦苦挣扎了两天。

【问题讨论】:

  • 你应该找别的地方阅读。第一个是危险代码,对SQL注入开放,第二个代码毫无意义。

标签: php mysql while-loop


【解决方案1】:

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

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;

【讨论】:

  • @miken32 。原始代码..选择所有文章并为每个文章执行用户选择..这在单个查询中执行..不需要(在这种情况下)参数查询..
  • 谢谢@scaisEdge 我刚刚尝试过并且有效。 miken32 很抱歉误导了我,但我的自动更正在这个问题上陷害了我,“应该”是不应该的,你是绝对正确的。 ?
猜你喜欢
  • 2015-11-10
  • 2012-11-28
  • 2017-03-09
  • 2013-11-01
  • 1970-01-01
  • 2013-12-30
  • 2015-02-15
  • 1970-01-01
  • 2014-03-27
相关资源
最近更新 更多