user3150191 user3150191 - 4 years ago 95
PHP Question

Displaying data with MySQL and PHP for my e-commerce website

I have a database that I am pulling data from. On my original PHP script I run the query and fetch the data, then echo it out, but for some reason this second script I have is not working. The query's are identical on the each page, so I'm not sure why it is tell me this, but it's saying my

$price
variable is not defined.

This is the code that is not working properly:

$cartoutput = "";
$cartTotal="";
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){
$cartoutput = "<font>Your Cart is currently empty.</font>";
}else{
$i=0;
foreach ($_SESSION["cart_array"] as $each_item) {
$item_id = $each_item['item_id'];
$result = mysqli_query($con,"SELECT * FROM menuitem WHERE id='$item_id' LIMIT 1");
if (!$result) {
printf("Error: %s\n", mysqli_error($con));// Displays the error that mysql will generate if syntax is not correct.
exit();
}
while ($row = mysqli_fetch_array($result)) {
$product_name = $row["name"];
$price = $row["price"];
}
$pricetotal = $price * $each_item['quantity'];
$cartTotal = $pricetotal + $cartTotal;

$i++;
$cartoutput .="<font>Item $i &nbsp;&nbsp; - &nbsp;</font>"; $cartoutput .= $each_item['item_id'] . $each_item['quantity'] . "<br />";
}
}

?>


More specifically, the line:

$pricetotal = $price * $each_item['quantity'];


is causing the problem. Like I said before, I have another PHP script that is being used the same way, and doesn't give me any problems. Doesn't it look like
$price
is defined in the WHILE LOOP? I've tried coding it differently, and nothing is working. My end goal is to just echo
$cartTotal
, but I can't do that because I'm getting the error $price is not defined?

Answer Source

$price is defined in a while loop, so its context ends in the while loop. At the time you are trying to use it it does not exist anymore. Even if that was allowed, you would only read the last value of $price. You want to do the entire calculation in the loop. Change it to this:

while ($row = mysqli_fetch_array($result)) {
    $product_name = $row["name"];
    $price = $row["price"];
    $pricetotal = $price * $each_item['quantity'];
    $cartTotal = $pricetotal + $cartTotal;
    $i++;
    $cartoutput .="<font>Item $i &nbsp;&nbsp; - &nbsp;</font>"; $cartoutput .= $each_item['item_id'] . $each_item['quantity'] . "<br />";
}   
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download