简体   繁体   中英

PHP product price and quantity does not multiply

I am trying to build an ecommerce site and in my cart page the quantity and product price does not multiply. It returns 0. If the user adds a product in the cart it returns the quantity 1 and the price 0, it he adds another one the quantity is updated and the price is 0. The $price= $price * $each_item['quantity']; doesn't work properly. Here is the code. Thank you so much for your answers!

$i=0;
foreach($_SESSION["cart_array"]as $each_item){
    $i++;
    $item_id=$each_item['item_id'];
    $sql=mysql_query("SELECT*FROM products WHERE id='$item_id' LIMIT 1");
    while($row = mysql_fetch_array($sql)){
        $product_name= $row["product_name"];
        $price=$row["price"];
    }
    $price= $price * $each_item['quantity'];
    $cartOutput.= "<h2>Product number: $i</h2>";
    $cartOutput.= "<p>Product ID:".$each_item['item_id']."</p>"."<br/>";
    $cartOutput.= "<p>Quantity:".$each_item['quantity']."</p>"."<br/>";
    $cartOutput.= "<p>Product name:".$product_name."</p>" ."<br/>";
    $cartOutput.= "<p>Price:".$price ."</p>"."<br/>";
}
  1. Use mysqli or PDO instead. mysql is deprecated and can lead you to a whole lot of trouble. Think about SQL Inyection.

Here is more info about PDO http://php.net/manual/en/ref.pdo-mysql.php

Here is info about mysqli http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

  1. Make sure data is added to the session array when an item is added to the "cart".. A good practice could be to set quantity as 1 by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM