PHP and user input - Changing the quantity in the basket

Hi,

I am designing a basket for a web site. If you click add to basket it takes the user to the basket with quantity 1 of the item clicked in their basket.

I have got the box with the quantity within it and the user can change the quantity by deleting the number and typing in a number for themselves. What I do not have is an update button. How can I use PHP to understand/store what the user has typed in and then how can I get an update button to then refresh the quantity and also the total prices?

IF THIS IS NOT POSSIBLE WITHOUT JAVASCRIPT would you suggest I use a Drop Down Menu choice (Quantity 1, 2 , 3, 4, 5, 6, 7, 8, 9, 10)
Matt.

It’s just another form, submit to update.php (for example) and update the values accordingly. :slight_smile:

So it’s possible without Java Script…?

If so, how do I write the code to say

userinput=$quantity;
update $quantity in MySQL table;
ShowCart;

Exactly the same way as you used to add a product, except update it.

The main problem I have is getting the user-input. Maybe you misunderstood? There is a box within the basket, the user can change the quantity from 1 to 10 by deleting 1 and typing in 10. But this user input needs to be updated in the MySQL database and also appear/calculate properly in the basket.

Furthermore I would like it to work with BOTH the UPDATE and the CHECKOUT buttons. So, if they click UPDATE the new quantity and prices show up in the basket. If they click CHECKOUT (after updating the quantity) the calculations are made on the next page (at the CHECKOUT).

You said use forms, does the form somehow store userinput=$quantity?

Add product is done with a link with a defined URL. The quantity box is not linkable and cannot link to a URL (Unless the quantity can be passed to the button somehow then the button can be the link providing the URL - can I get the value that the user inputs into the link from the UPDATE button?).

Matt.

You need a form similar to this:-


<form action="update.php" method="post">
  
  <input type="hidden" name="item[1][id]" value="100" />
  <input type="text" name="item[1][qty]" value="1" />
  
  <input type="hidden" name="item[2][id]" value="200" />
  <input type="text" name="item[2][qty]" value="2" />
  
  <input type="submit" name="action" value="update" />
  
</form>

Where id is the product id, and qty is current quantity. You’ll then need a PHP script to manage this submission and update your cart.


<?php
if('POST' === $_SERVER['REQUEST_METHOD']){
  if('update' === $_POST['action']){
    
    $items = $_POST['item'];
    
    foreach($items as $item){
      
      list($id, $qty) = $item;
      
      #UPDATE cart SET qty = $qty WHERE product_id = $id AND user_id = $_SESSION['user_id']
      
    }
    
  }
}

The examples I’ve provided won’t work but should help you out.