Pull several images of the same id in bd

3

I'm having a hard time pulling into the front end 4 images of the same id I have in the database.

I was able to normally insert the images into the database, I am using two different tables.

Follow the database below the first one:

Tabela: produtos
id  nome       descricao             slug
1  produto um  descricao do produto  produto-um

The second is below:

tabela:produto_imagens
id  produto_id  imagens
1      1        hsaudhuahdsu.jpg
2      1        gsagaasftfsa.jpg
3      1        assdoakdaado.jpg

follow the php code below:

<?php
$url = explode('/',$_GET['url']);
$produto = MySql::run()->prepare("SELECT * FROM 'produto' WHERE slug = ?");
$produto->execute(array($url[0]));// código para ver se a url existe.
if($profile->rowCount() == 0){
die("a página não existe!");

}
foreach ($produto as $key => $value) {
$produto->fetchAll();
$imagens = MySql::run()->prepare("SELECT * FROM 
'produto_imagens' WHERE produto_id = $value[id]");
$imagens->execute();

?>
// nao coloquei as tags do php pq se nao o 
//codigo nao aparece para vcs.

<h2>Nome do produto:  echo $value['nome'];<h2>
<h3>Descrição do produto</h3>
<p>echo $value['descricao']; </p>
<?php }?>//fecha foreach"produto".

<?php
foreach ($imagens as $key => $value) {
$imagens = $imagens->fetch()['imagem'];

?>
<img src='echo $imagens'>   
<?php } ?>//fecha foreach $imagens.

So, I can recover all the data from the "products" table, and from the "image_products" table I can recover only the first one, and if it replicates the code it returns the same image. Does anyone know how I pull from the database all the images from the same id of the products table and show it to the user on the front end?

    
asked by anonymous 16.10.2018 / 16:39

1 answer

2

You are overwriting the images variable.

foreach ($imagens as $key => $value) {
    $imagens = $imagens->fetch()['imagem']; // <====== AQUI
                                            // Já existe a variável $imagens

So this is only showing 1 image, because you are always overwriting it with the name of an image, inside the foreach.

You are overwriting the images variable.

Another thing I found in your code that I found strange was this part:

<img src='echo $imagens'>   

You are running echo without PHP tags before.

Corrected code

foreach ($imagens as $key => $value) { ?>
    <img src="<?php echo $value ?>">
<?php }
    
16.10.2018 / 19:20