Reputation: 5132
I have two pages, product.php and viewcart.php. When a user clicks on a button on product.php, it adds the product to the back-end (along with it’s attributes) and goes to viewcart.php. The data gets submitted to viewcart.php through the code below. There are some php variables that need to get passed in addition to a value from a textbox on product.php (the variable is “val” below).
<script language="javascript">
function test()
{
var val=document.getElementById("textarea").value;
var hrf="viewcart.php?retailer=<?php echo $retailer?>&link=<?php echo $link; ?>&price=<?php echo $price; ?>&title=<?php echo $title; ?>&options="+val;
document.getElementById("a_link").href=hrf;
}
</script>
<a href ="#" id="a_link" onclick="test();" class="btn btn-success" type="submit"><i class="icon-shopping-cart icon-white"></i> Add to Cart</a>
On viewcart.php, the product gets added to the back-end and then gets displayed via the code below:
@$link = $_GET['link'];
$price = $_GET['price'];
$title = $_GET['title'];
$retailer = $_GET['retailer'];
$options = $_GET['options'];
$session = session_id();
$_SESSION['sess_var'] = $session;
//connect to database code here
mysql_query("INSERT INTO sessionid (sessionid, link, retailer, price, title, qt, options) VALUES('$session' , '$link', '$retailer', '$price', '$title', 1, '$options') ");
The problem I am having is when the user refreshes viewcart.php; the product gets added again because of the code above. How do I ensure the product gets added to the database ONLY if the user clicks on the submit button on product.php (and not by refreshing viewcart.php or clicking the “back” button to get to viewcart.php)?
Upvotes: 1
Views: 123
Reputation: 3932
Technically if you refresh the page with the same POST data, as far as I know, you will have the same referrer, so you shouldn't try to check whether the referrer is product.php .
What you should do is use an update/insert MySQL query. First make sure that you also insert the primary key in your query (so that when the page is refreshed, it will be the same key), then use something similar to:
INSERT INTO sessionid (id,a,b,c) VALUES (0,1,2,3)
ON DUPLICATE KEY UPDATE id=id;
Lastly, don't forget to sanitize your input.
Upvotes: 1
Reputation:
// where submit is the name of the forms submit input/button
if ($_GET["submit"]) {
// add to cart
} else {
// products should have already been added
}
Upvotes: 0
Reputation: 6126
This problem is often solved using the POST/Redirect/GET pattern. Generally if you have a file called viewcart.php then it should just display the cart and not add a product as well.
Upvotes: 0
Reputation: 3713
You have to ckeck if the row has already been added. So use a select and if "fetch()" return something different than "false" insert your datas.
Upvotes: 0