简体   繁体   中英

How to check if a submit button has already been clicked in PHP

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> &nbsp;&nbsp;&nbsp;
  <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`

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.

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");
}

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.

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