how to use foreach

Asked

Viewed 169 times

4

Hi, I’m here to enlist the help of friends. I have this code below to list all products and be registered, but I’m not able to list them on the same page using foreach. Could your friends give me a hint of where I’m going wrong? Hugs to all, and from now on my thanks for the 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 -->
  • What’s the problem? the only thing I see that might be going wrong is the database not being with the structure or the data you expect.

  • Where does this variable come from $produtos?

1 answer

1


It seems that the variables are not receiving the correct values, check whether mysql_query() did not return error, after that do mysql_fetch_array($query) in a while and print the products if you want to store the items in array do $produtos[] = $res; The code should stay this way

$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 } ?>
  • while() : and then endwhile; to be more organized!

  • Thanks for the help rray, it worked fine. Hugs, and until next time.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.