how to use the foreach

4

Hello, I'm here to ask for the help of your friends. I have this code below to list all the products and to be registered, but I am not able to list them on the same page using the foreach. Would my friends give me a hint of where I'm going wrong? Hugs to all, and thanks for your attention.

   <?php include 'conexao.php';

   $codigo = $_POST['codigo'];
   $titulo = $_POST['titulo'];
   $imagem = $_POST['imagem'];
   $preco = $_POST['preco'];

   $query = mysql_query("SELECT * FROM produtos");
   $res = mysql_fetch_array($query);
   ?>

   <div class="center_content">
   <div class="center_title_bar">Produtos</div>

   <?php
   if (isset($produtos)) {
      foreach ($produtos as $res){
   ?>

   <div class="prod_box">
   <div class="top_prod_box"></div>

   <div class="center_prod_box"> 

   <div class="product_title"><a href="detalhe.php?codigo=<?php echo $res["codigo"];?>"><?php echo $res["titulo"]; ?></a></div>

   <div class="product_img"><a href="detalhe.php?codigo=<?php echo $res['codigo']; ?>"><img width="100" height="auto" src="upload/<?php echo $res['imagem'];?>" alt="" title="" border="0" /></a></div>

   <div class="prod_price"><span class="price">R$ <?php echo $res["preco"]; ?></span></div> 

   </div>

   <div class="bottom_prod_box"></div>             
   </div> 

   <?php
     }}
   ?>

   </div><!-- end of center content -->
    
asked by anonymous 30.08.2015 / 20:07

1 answer

1

It seems like the variables are not getting the correct values, make sure mysql_query() did not return error, then make mysql_fetch_array($query) in a while and print the products, if you want to save the items in array do $produtos[] = $res ; The code should be left unattended

$query = mysql_query("SELECT * FROM produtos") or die(mysql_error());
while($res = mysql_fetch_array($query)){?>
   <div class="product_title"><a href="detalhe.php?codigo=<?php echo $res["codigo"];?>"><?php echo $res["titulo"]; ?></a></div>
   <div class="product_img"><a href="detalhe.php?codigo=<?php echo $res['codigo']; ?>"><img width="100" height="auto" src="upload/<?php echo $res['imagem'];?>" alt="" title="" border="0" /></a></div>
   <div class="prod_price"><span class="price">R$ <?php echo $res["preco"]; ?></span></div> 

<?php } ?>
    
30.08.2015 / 21:40