而 if 语句中的循环位于 foreach 循环中.效果不佳


While loop within if statement that is within a foreach loop... not working well

我希望我能很好地解释这一点......我有一个名为 $departments_ids = 数组 (1, 2, 3) 的数组。

对于数组中的每个部门,我需要显示存储在数据库中的注释列表。我想出了这样的东西:

foreach ($departments_ids as $department_id) {
$query = "SELECT page_posts.post_id, page_posts.post, page_posts.post_date_time, 
users.profile_type_id, users.first_name, users.last_name, users.picture ".
"FROM page_posts ".
"INNER JOIN users ".
"USING (user_id) ".
"WHERE dep_id = $department_id ".
"ORDER BY post_date_time ASC";
$data = mysqli_query($dbc, $query);
     if(mysqli_num_rows($data) != 0) {
         while ($row = mysqli_fetch_array($data)){
         Here goes the code to print each comment 
         }
     }
     else {
        <p> Sorry, there are no comments yet. Don''t  
        be shy, be the first one to post!</p>
        }
}

(注意:我省略了部分代码以简化解释)

代码运行良好,问题是它只打印每个部门的第一条注释,而不是存储在数据库中的所有注释。这就像每个部门只读取一次代码,然后它移动到下一个部门。如果我很好地理解这一点,我相信一旦它点击 if 语句并看到有多个评论,它应该继续阅读 while 语句,while 语句应该处理所有评论,但由于某种原因它不起作用。我读到有人有类似的问题,但仍然无法弄清楚为什么它不起作用。

你可以

试试这个:

$query = "SELECT page_posts.post_id, page_posts.post, page_posts.post_date_time, users.profile_type_id, users.first_name, users.last_name, users.picture ";
$query .= "FROM page_posts INNER JOIN users USING (user_id) WHERE 1=1 AND";
$query .= "(";
foreach ($departments_ids as $department_id) {
    $query .= " dep_id=$department_id OR ";
}
$query .= ")";
$query .= " ORDER BY post_date_time ASC";
$data = mysqli_query($dbc, $query);
if(mysqli_num_rows($data) > 0) {
    while ($row = mysqli_fetch_array($data)){
        /*** Here goes the code to print each comment  */
    }
} else {
    echo "<p> Sorry, there are no comments yet. Don''t be shy, be the first one to post!</p>";
}

编辑:

$query .= " dep_id=$department_id OR ";

为 1、2 或 3。

我终于想通了问题所在...这是一个菜鸟的错误:

我有 2 个相互冲突的$query......我有 1 个查询来查找评论,然后是另一个查询来查找对这些查询的响应......当我删除第二个查询只是为了测试代码时,我在问题中提供的代码工作得很好;因此,我将第二个查询更改为 $query 2...问题解决了。

感谢您的帮助!