I have an add to cart code in php. I created a code that when the user select an already existing product in the cart the quantity of the existing product and the inputted new quantity will be added to each other
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pos";
$id=$name =$price=$quantity_order=$old_quantity_order = "";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$id = $_POST['id'];
$name = $_POST['name'];
$price = $_POST['price'];
$quantity_order = $_POST['quantity_order'];
$subtotal = $price * $quantity_order;
}
$check="SELECT * FROM cart WHERE id = $id";
$sql = mysqli_query($conn,$check) or die(mysql_error());
if (mysqli_num_rows($sql) > 0) {
while($res = mysqli_fetch_row($sql))
{
$old_quantity_order=$res['quantity_order'];
}
$new_quantity_order =$quantity_order + $old_quantity_order;
$up = mysqli_query($conn, "UPDATE cart SET quantity_order='$new_quantity_order' WHERE id=$id");
}
else {
$sql =mysqli_query($conn,"INSERT INTO cart (id,name, price,quantity_order,subtotal)
VALUES ('$id', '$name', '$price','$quantity_order','$subtotal')");
}
header("Location:pos.php")
I tried to fetch the existing quantity in the database and rename it as $old_quantity_order and to be added on the inputed quantity which is $quantity_order.
But the only value that enter my database is the value of $quantity_order, the $old_quantity_order is 0.
This is the form I used to add a quantity_order to the cart.
<div class="form-group">
<form method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<input type="hidden" name="name" value="<?php echo $name; ?>"/>
<input type="hidden" name="price" value="<?php echo $price; ?>"/>
<input type="hidden" name="quantity" value="<?php echo $quantity; ?>"/>
<label>Quantity</label>
<input class="form-control" type="number" name="quantity_order" placeholder="quantity" min="1" max="<?php echo $quantity; ?>" />
<input class="btn btn-primary" type="submit" name="add_to_cart" formaction="add_to_cart.php" id="add_to_cart" value="Add to Cart" OnClick="return mess();">
<input class="btn btn-success" type="submit" name="process" formaction="process_frompos.php" value="Process"></a>
</form>
</div>