Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

mysqli

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.

like image 823
Rookie Avatar asked Feb 28 '26 15:02

Rookie


1 Answers

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.

like image 159
Alex Avatar answered Mar 02 '26 04:03

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!