0

I am looking for clarification on while loop and foreach loop...

say I have 2 tables both table have a field called MYID, MYID will be the same for both tables..

How would you accomplish echo certain fields once while another field multiple times.

example

while ($row = mysqli_fetch_assoc($result)) {

        $MYID = $row['MYID'];        
        $FullName = $row['FullName'];    
        $Photo = $row['Photo'];        


    // Display this info once     
    echo "<div>$FullName<br>Photo</div>";   


   // Array for table 2 row    
   $Images[] = array($row['Images']);

   foreach ($Images as $img){       
   //Display this row as many times as needed by data in this row.

       echo <div>$img</div>;
   }
}  
10
  • Can you add examples of input data and result you want/expect to get? Commented Apr 27, 2017 at 23:06
  • $Images contains all the images from all the rows you've processed so far, not just the current row. Commented Apr 27, 2017 at 23:07
  • If $row['Images'] contains a comma-separated list of images, you should use explode() to split it into an array, and then loop over that. Commented Apr 27, 2017 at 23:08
  • example here I'm trying to create how each profile user there images is under there profile bodyelectrictattoo.com/our-team Commented Apr 27, 2017 at 23:09
  • I want to create a profile page that displays just like that page with data from the database but the info will echo out the first profile 10 times for each image added.. and not other profile shows. Commented Apr 27, 2017 at 23:11

1 Answer 1

0

If you're using GROUP_CONCAT, $row['Images'] will be a comma-separated list, which you can split with explode().

while ($row = mysqli_fetch_assoc($result)) {

    $MYID = $row['MYID'];        
    $FullName = $row['FullName'];    
    $Photo = $row['Photo'];        
    // Display this info once     
    echo "<div>$FullName<br>Photo</div>";   

    // Array for table 2 row    
    $Images = explode(',', $row['Images']);
    foreach ($Images as $img){       
    //Display this row as many times as needed by data in this row.
       echo <div>$img</div>;
    }
}  
Sign up to request clarification or add additional context in comments.

2 Comments

that work as needed but I only shows 1 profile now there are 2 in the database
Sounds like a problem with your query. Did you use GROUP BY properly? I asked above for you to add the query to the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.