Filling an HTML table with MySQL data (multiple images for a table cell)

I am trying to populate an HTML table with data coming from my database. Here I saved the β€œservices” in my table. Each service can have multiple images. Therefore, when filling out the table, it should have 3 cells tables, one for the "service name", and the second for the "description" and the third for the images.

This my SQL query looks like this:

 $prep_stmt = " SELECT s.id , s.name , s.description , i.image , i.image_path FROM services s LEFT JOIN images i ON i.service_id = s.id"; 

This is what my while looks like:

 while ($stmt->fetch()) { $html = "<tr>\n"; $html .= " <td><input type='checkbox'></td>\n"; $html .= " <td>\n"; $html .= " <a href='' class='name'>{$name}</a>\n"; $html .= " </td>\n"; $html .= " <td class='view_html'>{$description}</td>\n"; $html .= " <td>\n"; --- My images should be display here ---- $html .= " </td>\n"; $html .= "</tr>\n"; //Add output to array $output[] = $html; } 

My problem is how to display multiple images in one table cell? If one service has only one image, I can do it, but I have several images, then I'm not sure how to do it.

+5
source share
1 answer

Change your sql code as below and try

  $prep_stmt = " SELECT s.id , s.name , s.description , (select group_concat(i.image_path,'/',i.image) from images i where i.service_id = s.id) as img FROM services s"; 

Then use this HTML

  while ($stmt->fetch()) { $html = "<tr>"; $html .= " <td><input type='checkbox'></td>"; $html .= " <td>"; $html .= " <a href='' class='name'>{$name}</a>"; $html .= " </td>"; $html .= " <td class='view_html'>{$description}</td>"; $html .= " <td>"; $img_array=explode(",",$img); foreach($img_array as $im){ if($im==''){ $html .= " <img src='default.jpg'>"; }else{ $html .= " <img src='{$im}'>"; } } $html .= " </td>"; $html .= "</tr>"; //Add output to array $output[] = $html; } 
+7
source

All Articles