【问题标题】:While loop with Group By only results in one line使用 Group By 的 While 循环仅产生一行
【发布时间】:2018-11-03 09:01:14
【问题描述】:

此查询在 phpMyAdmin 中产生预期的 4 行(见下图):

SELECT * FROM messages WHERE send_from = 65 OR send_to = 65 GROUP BY `property_id`

如果我在我的 php 网站中循环遍历结果,我只会从 phpMyAdmin 获得结果表的最后一行作为输出。

      $property_id_text = "property_id";
  $list_messages = $mysqli->prepare("SELECT message_text FROM messages WHERE send_from = ? OR send_to = ? GROUP BY ?");
  $list_messages->bind_param("sss", $user_id, $user_id, $property_id_text);
  $list_messages->execute();
  $list_result = $list_messages->get_result();


  if ($list_result):
      if(mysqli_num_rows($list_result)>0):
          while($list_message = $list_result->fetch_assoc()):

            $nachrichten_liste = $nachrichten_liste . '<div>' . $list_message['message_text'] . '</div>';

            endwhile;
      endif;
  endif;

知道为什么$nachrichten_liste 不包含表格中的所有行吗?我希望上图中的所有消息都包含在$nachrichten_liste

更新

如果我将 GROUP BY 运算符“property_id”直接放在准备好的语句中,它就可以工作

$list_messages = $mysqli->prepare("SELECT message_text FROM messages WHERE send_from = ? OR send_to = ? GROUP BY property_id");

【问题讨论】:

  • 我不认为这是一个覆盖问题,因为我有这样的变量分配: $nachrichten_liste = $nachrichten_liste 。 '
    ' ......
  • @Smartpal 结果:文本 4

标签: php mysqli while-loop group-by


【解决方案1】:

当您将值 "property_id" 绑定为文字而不是列名时,您正尝试 GROUP BY 文字(无论如何您都不能这样做)。这意味着它是按始终相同的东西分组的,并且所有行都在 1 个组中。您必须在语句中包含变量...

  $property_id_text = "property_id";
  $list_messages = $mysqli->prepare("SELECT message_text 
                               FROM messages 
                               WHERE send_from = ? OR send_to = ? 
                               GROUP BY $property_id_text");
  $list_messages->bind_param("ss", $user_id, $user_id);

除非您知道 $property_id_text 不会成为 SQL 注入的潜在来源,否则不建议使用。

您还应该为message_text 提供某种聚合函数,以便它知道应该是哪一个(即使它们相同)。阅读https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html

【讨论】:

  • 很好,这行得通!我在 GROUP BY 之后直接输入了列名“property_id”(没有变量),因此我认为没有机会进行 SQL 注入,对吧?
  • 如果您知道按字段分组的内容始终是什么,最好对其进行硬编码,并使语句更安全。
猜你喜欢
相关资源
最近更新 更多
热门标签