Reputation: 23
sqlQueryImage ThisWhatIgetinPHP
i have tried this but it keeps displaying me just the first image of every article i don't know how display multiple image for one article
$result = $db->prepare("SELECT article.titreArticle, article.textArticle,
article.idArticle, article.dateArticle, GROUP_CONCAT(images.images) AS IMG
FROM article LEFT JOIN images
ON article.idArticle = images.idArticle
GROUP BY article.idArticle");
for ($i = 0;
$row = $result->fetch();
$i++){
?>
<h1 style="text-align: center"><?php echo $row['idArticle']; ?></h1>
<hr>
<img style="width: 300px" src="images/<?php if($row ['IMG'] !=null ) {
$value = $row['IMG'];
}
$values = explode(",", $value);
echo $values[0];
?>">
Upvotes: 0
Views: 277
Reputation: 10226
The aim of GROUP_CONCAT is to return each value within each GROUP, concatenated in the same field.
You expect to have several images for certain groups, however you only display one image, the first one encountered : echo $values[0];
If you want to display all images of a group, you have to make a second loop on your array of images, to print each element.
So you have your main loop on row, and a second loop on images.
Try this:
<?php
$result = $db->prepare("SELECT article.titreArticle, article.textArticle,
article.idArticle, article.dateArticle, GROUP_CONCAT(images.images) AS IMG
FROM article LEFT JOIN images
ON article.idArticle = images.idArticle
GROUP BY article.idArticle");
// FIRST LOOP ON ROWS
for ($i = 0; $row = $result->fetch(); $i++){
?>
<h1 style="text-align: center"><?php echo $row['idArticle']; ?></h1>
<hr>
<?php
$images = ""; // we will store all our images for this row here (if any)
if($row ['IMG'] !=null ) {
$value = $row['IMG'];
$values = explode(",", $value);
// SECOND LOOP ON IMAGES
foreach($values, $imgsrc){
$images .= '<img style="width: 300px" src="images/'.$imgsrc.'">';
}
echo $images; // output all images
}
?>
Upvotes: 2