Search code examples
phpmysqlloopswhile-loopnested-loops

while loop not showing all the data gathered from database


while loop not showing all the data gathered from database .. showing only last gathered item in the page. rather than showing all.

<?php 
    include "connect_to_mysql.php"; 
    $dynamicList = "";
    $sql = mysql_query("SELECT * FROM product ORDER BY date DESC LIMIT 6");
    $productCount = mysql_num_rows($sql); // count the output amount
    if ($productCount > 0) {

    //here is problem in this while loop.. dont know why it is not gathering all the items.


       while($row = mysql_fetch_array($sql)){ 
         $id = $row["id"];
         $product_name = $row["p_name"];
         $price = $row["price"];
         $date_added = strftime("%b %d, %Y", strtotime($row["date"]));
         $details = $row["details"];
         $category = $row["category"];
         $subcategory = $row["sub_category"];
         $category2 = $row["category2"];
         $img_name = $row["img_name"];
         $v_id = $row["v_id"];
         $v_name = $row["v_name"];
         $v_number = $row["v_number"];
         $v_email = $row["v_email"];

         $dynamicList="

           <div id=\"single_product\" style=\"float:left; margin-left:20px; padding:10px;\">

           <h3> $product_name  </h3>
           <h3> <img src='pics/$img_name' width='200px' height='200px'/> </h3>
           <p><b><center> RUP $price </center></b></p>

           <a href=\"details.php\" style=\"float:left; font-size:20px;\">Details</a>
           <a href=\"cart.php\" style=\"float:right; font-size:20px;\">Add To Cart</a>

           </div>            
         ";

       }
   } else {
        $dynamicList = "We have no products listed in our store yet";
   }
   mysql_close();
?>

i am stucked here plz get me out me out from here


Solution

  • You are using

    $dynamicList="...
    

    In your loop. I assume you are echoing the $dynamicList later in the code. You need to use text concatenation rather than just an =

    So do

    $dynamicList .= "...
    

    and it will add to the string each time round the loop rather than overwrite it