Reputation: 756
I basically have an updatecart.php script which INSERTS data into a database table once the submit button from the HTML page has been clicked, it then goes to display.php where the updated content is shown. The problem I have is that I have a quantity field in my displayed data and if the user clicks the submit button (add stuff to shopping cart) then I want the quantity to increase by how much quantity the user has chosen in in the dropdown menu in the HTML page. Right now if the user clicks the submit button again nothing happens as it is the same data being added to the database table.
Code:
HTML:
<form name = "AddToCart" action ="../updatecart.php" method='post'>
Quantity:
<select name="Quantity">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input type ="submit" name ="Add" value="Add To Cart"/>
</form>
updatecart.php:
<?php
// Connection to database omitted
$Quantity = $_POST['Quantity'];
$query = "INSERT INTO Cart VALUES
('1', 'The Fiqh of Dawah', '18.00', 'Books', '$Quantity')";
mysql_query($query);
header("location:displaycart.php");
?>
display.php:
//Not necessary to show this as it simply uses `echo` to create a table and display the whole table data with `SELECT * FROM Cart`
Upvotes: 0
Views: 6666
Reputation: 4523
You need to check if the item already exists in the cart by doing a SELECT
first, and then choose between an INSERT
(if no rows exists for this item in the cart) or an UPDATE
(if this item is already in the cart).
In MySql, You can also do it by using INSERT ... ON DUPLICATE KEY UPDATE
Syntax. But You will need to have a primary key to do so.
Upvotes: 1
Reputation: 1250
You can do a check in your updatecart.php at the top to check if Submit has been clicked.
Something like
isset($_POST['Add']) {
// insert data into DB
}
else {
// redirect somewhere as they havent clicked Submit button
}
You should also be running your user data through a check/sanitize before you input into your DB.
Upvotes: 0
Reputation: 1163
you can use isset($_POST['Add'])
to check the submit button submitted or not
like
if(isset($_POST['Add']))
{
$Quantity = $_POST['Quantity'];
$query = "INSERT INTO Cart VALUES
('1', 'The Fiqh of Dawah', '18.00', 'Books', '$Quantity')";
mysql_query($query);
header("location:displaycart.php");
}
Upvotes: 0