0

I don't know what is wrong with my code. supposingly, it should be populating all the items that I have in my database(id) however, it just tell me how many item I have in my database instead of listing out all the ids of products that I have in my database

Can someone help to pointed out my mistakes? I'm following a tutorial on youtube on making the shopping cart.

<?php
$product_list = "";
$sql = mysql_query("SELECT * FROM supermarket");
$productCount = mysql_num_rows($sql);//count output amount
if($productCount > 0){
    while($row = mysql_fetch_array($sql)){
        $id = $row["id"];
        $product_list = "$id<br>";
    }
}
else{
    $product_list = "You have no products listed in your store yet";
}
?>
  • You are erasing $product_list content every time you pass inside the loop. The only thing stocked inside $product_list is the last id in your query. – GeoffreyB Jan 16 '14 at 11:12
  • you overwrite your $product_list every sequence of your loop. store in in a array: `$product_list[] = "$id"` – Gert B. Jan 16 '14 at 11:12

3 Answers3

4

You're overwriting your $product_list variable. Instead you need to take all your id in array variable,

$product_list = array();
if($productCount > 0){
    while($row = mysql_fetch_array($sql)){
        $id = $row["id"];
        $product_list[] = $id;
    }
}
print_r($product_list);

Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Rikesh
  • 26,156
  • 14
  • 79
  • 87
  • This is not a complete code. You need to add this after your line `$productCount = mysql_num_rows($sql);`. Just replace this with your current `if condition`. – Rikesh Jan 16 '14 at 12:26
  • What is the column name for `item id` ? – Rikesh Jan 16 '14 at 12:31
1

Every time round your while loop, you're overwriting the previous contents of $product_list. You presumably want to concatenate instead using the .= operator, like this:

while($row = mysql_fetch_array($sql)){
    $id = $row["id"];
    $product_list .= "$id<br>";
}

I'm assuming here that you're outputting $product_list later (some time after the loop), e.g.:

echo $product_list;
Peter Bloomfield
  • 5,578
  • 26
  • 37
0

If you want all data from your product:

$product_list = array();
  if($productCount > 0){
  while($row = mysql_fetch_array($sql)){
    $id = $row["id"];
    $product_list[$id] = $row;
  }
}
print_r($product_list);

you have to store it in a array, you overwrite you $product_list every sequence of the while loop its not the count you get btw, its the last id fetched you get returned in your code

Gert B.
  • 2,282
  • 18
  • 21