Thursday, 30 August 2018

While looping in the if statement in a loop foreach & hellip; does not work well

I hope I can explain this well... I have an array called $departments_ids = array (1, 2, 3).

for each department within the array I need to display a list of comments stored in the database. I came up with something like this:
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>
        }
}

(Note: I ommitted part of the code to simplify the explanation)
The code works well, the problem is that it IS ONLY PRINTING THE FIRST COMMENT FOR EACH DEPARTMENT instead of all the comments stored in the database. It's like the code is read only once for each department and then it moves to the next department. If I understand this well I believe that once it hits the if statement and sees that there is more than one comment it should continue reading the while statement, and the while statement should take care of all the comments, but for some reason it is not working. I read about people with similar problems, but still can't figure out why it isn't working.

You could try this :
$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>";
}

Edit :
$query .= " dep_id=$department_id OR ";
Is either 1 or 2 or 3.

0 comments:

Post a Comment