i am learning to build a shopping cart, the problem is every time i hit refresh it automatically increases the quantity for the added item, and even i close the window and run the file again i see my cart there means it does not destroy the session, i will give you the example so you can understand because my english is not that good,
Problem-1:Please read the Example-1, Example-2 and Summary
Example-1: I added two tea in the cart, than i added 3 coffee in the cart, its work fine but i notice if i hit refresh now it increases the coffee quantity automatically, why its doing it and what the solution. note: This time I Added coffee last in the Cart
Example-2: In last example i added the tea first and coffee last, so it increases the coffee when i hit refresh, but in this example i reverse the system means first i added coffee first than i added tea in the end, if i hit refresh now it increase the quantity for tea, note: This time I Added Tea last in the Cart
Summary: When i hit refresh it increases the quantity of last added item in the cart, if i hit refresh 5 times it going to increase the quantity 5 times means it does not matter how many times i hit refresh each time it increases the quantity, i dont know why its doing it,
Second Problem: As i am a begenner so it might be silly probmlem, i am using session, as far i know when i close my window and run the application again cart should be empty, but its not empty the each and every items which i added last time are still there with the last added quantity
Example: Lets say i have two tea in my cart and three coffee, and one t-shirt, i close my window and run the application again, i can see my last cart still there, means i still have two tea, three coffee and one t-shirt in the cart, as far i know i should not have any thing in the cart because i closed window.
Note: I am using XAMPP
Here is my code
<?php
session_start();
if (isset($_GET['add']))
echo $_SESSION['cart_'.$_GET['add']]+='1';
}
$db=mysqli_connect ('localhost','root','','dummyphpmyadmin') or die (mysql_error());
function products (){
$db=mysqli_connect ('localhost','root','','dummyphpmyadmin') or die (mysql_error());
$query= mysqli_query($db,"SELECT * FROM products");
while ($x= mysqli_fetch_array($query)){
echo $x['name'].'<br/>'.
$x['description'].'<br/>'.
$x['price'].'<br/>'.
'<a href="cart.php?add='.$x['id'].'">Add</a>'.'<br/>';
}
}
function cart ()
{
foreach ($_SESSION as $name => $value)
{
if (substr($name, 0 ,5)=='cart_')
{
$db=mysqli_connect ('localhost','root','','dummyphpmyadmin') or die (mysql_error());
$id = substr ($name , 5 , (strlen($name)-5));
$get= mysqli_query($db,"SELECT id, name, price FROM dummyphpmyadmin.products
WHERE id=$id");
while ($get_row=mysqli_fetch_array($get))
{
$total = $get_row['price'] * $value;
echo $get_row['name'] . 'X' .$value. ' @ '
.$get_row['price'] .' = ' . $total. '<br />';
}
}
}
}
cart();
products()
?>