0

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>
Vanie
  • 1
  • 2
  • Could you please help me sir to correct my code,it's alright even if it take some time. I just created this code by merging and editing the sources that I found so Im not sure what my errors are. – Vanie Feb 10 '19 at 15:34
  • the $old_quantity_order += $res['quantity_order'] still doesn't work. – Vanie Feb 10 '19 at 15:37

1 Answers1

0

Run the below code and see if you get any PHP Errors.

$servername = "localhost";
//it is BAD practise to connect to your DB as root. 
$username = "pubuser";
$password = "";
$dbname = "pos";
$id = $price = $quantity_order = $old_quantity_order = 0;
$name = "";

$conn = mysqli_connect($servername, $username, $password, $dbname);

//
// $_SERVER["REQUEST_METHOD"] is so common, and I don't like it as it's 
// not a clear check. Intead check that the array is populated. 
//
if (\is_array($_POST) && \count($_POST) > 0) {

    // Id is usually a digit number.  
    // So force to type. NEVER trust user input!
    $id = (int) $_POST['id'];

    $name = $_POST['name'];     
    // $price may be a float or an int?             
    $price = (float) $_POST['price'];
    $quantity_order = (int) $_POST['quantity_order'];
    $subtotal = $price * $quantity_order;
}

//
// So what happens here, if POST has not been set?
//

// Only grab the rows you need from the database:
$check="SELECT quantity_order FROM cart WHERE id = $id";

// 1) Mysqli_error needs the connection variable.
// 2) Errors shold be logged to an error log, NOT thrown to output.  
// 3) USE PREPARED STATEMENTS
$sql = mysqli_query($conn,$check) or error_log(__LINE__." : ".mysqli_error($conn));

if (mysqli_num_rows($sql) > 0) {

    // Because you're calling only one row, you don't need to loop it. 
    $res = mysqli_fetch_row($sql);

    $new_quantity_order = $quantity_order +  $res['quantity_order'];

    $up = mysqli_query($conn, "UPDATE cart SET quantity_order =
          ".(int)$new_quantity_order." WHERE id = ".$id );
}
else {
    // Numerical column values in SQL do not need to be encased in quotes 
    // and this slows down transactions.
    $sql = "INSERT INTO cart (id, name, price, quantity_order, subtotal)
    VALUES ( ".$id.", '".$name."', ".$price.", ".(int)$quantity_order." ,".$subtotal.")";

    mysqli_query($conn, $sql) or error_log(__LINE__." : ".mysqli_error($conn));
}

    // your header needs to have a semicolon ; at the end. 
    header("Location:pos.php");
    // header Locations MUST then be followed by an exit/die statement. 
    exit;

Useful links:

Community
  • 1
  • 1
Martin
  • 22,212
  • 11
  • 70
  • 132
  • Sir, it doesn't have any php error. But it still doesn't add the value of the quantities, it only read the new inputted quantity – Vanie Feb 10 '19 at 15:49
  • try `error_log(print_r($_POST,true));` near the top of your script. What does it show you? – Martin Feb 10 '19 at 15:53
  • It doesnt show anything, the values are still added to the cart and headed to the next php ,which is the pos.php. But the quantity still doesn't add up. – Vanie Feb 10 '19 at 16:02
  • Then that means your POSTed data is empty. The problem is not on this page but is on however you POST the data to the page. Please update your question. – Martin Feb 10 '19 at 16:18
  • Do you mean sir, that the error is on the previous php file? And why do I need to update the question? – Vanie Feb 10 '19 at 16:37
  • @Vanie update your question with the details of the page SENDING the `$_POST` data. Because this posted data appears to be empty,this is why your code is not working as you'd like. – Martin Feb 11 '19 at 10:05