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()
?>

Recommended Answers

All 10 Replies

Heh.. welcome to the world of "stored" values and URL management.

Since you are doing a GET (or a POST), the value gets stored in the URL. When you refresh the page, you are basically resending the URL with the parameters still in place.

So, your session variable (where you "store" the value) is simply doing what you are asking it to - the $_GET is set, so update the session variable by +1.

Tada!

The solution to your problem? Don't refresh. :-/

Or, you can play with URL rewrites, but then you are sort of defeating the use of "GET" as a way to keep a "trail" to a location...

There is nothing wrong with your code. Instead of refreshing, get rid of the the ?add=1 in the URL and hit enter.

Keep in mind, if you did this with a "POST" you would get a message telling you that you are "resending" data. It would not in any way solve your problem.

Hope that helps,

Ryan

The solution to your problem? Don't refresh. :-/

Not true. I would reccomend simply doing a redirect to the regular cart URL (without params) after you have updated the cart quantities. I put an example below. Since I don't know your URL's I improvised :)

if (isset($_GET['add']))
    $_SESSION['cart_'.$_GET['add']]+='1';
    header('Location: /cart.php');
}

Fair. But what if other params on the stack are also being tested. You have now blown away the stack. It's not that his script is wrong, its that he didn't understand the method of gets and posts. I would discourage a redirect, as it would just lead to further confusion and frustration down the line (unless that is a desired behavior.)

Member Avatar for diafol

I'm pretty sure you need to be storing this in a DB on each round of submissions, in which case, POST may be more applicable. Imagine the scenario that a security program shuts down the brwoser without warning (like my machine!!) when it scans, the user loses all that lovely data (well perhaps not with your weird session behaviour!).

So, making changes to the DB requires POST. I always advise posting to a different file for POST (followed by a redirect) as you don't want to resubmit the data on page refresh - so similar to what hag++ is suggesting for your url querystring.

Just a thought

I highly agree with diafol if you have time to change it. If not and ryantroop's above comment is a concern then you could always redirect the user to the cart with every param except the ones used to add items.

Thanks ryandrop , diafol and hag++,

ryandrop i am new so i only know that in get you can get value from the url, that's why i am storing my product id in the url and getting it through get methode,

hag++, i am using your methode but ryandrop say it might create some problem in the future, the solution you gave me its working fine and i do have to time to change cause i am just learning so i do have time its not for the somebody website, it just for me to understand it,

and diafol, are you suggesting me that i should create my shopping cart with POST methode, i did not understand theese line in your second paragraph

your comment <<<<<
I always advise posting to a different file for POST (followed by a redirect) as you don't want to resubmit the data on page refresh - so similar to what hag++ is suggesting for your url querystring.>>>>>> your comment finish.

and again thanks everyone hope you reply again

You are doing nothing wrong.

As long as you understand what the redirect is doing (basically clearing your GET/POST stack), you're fine :)

He suggested doing a POST (instead of a GET, which uses the URL), as it allows for more flexibility, and the ability to do a bit more behind the scenes without cluttering up a URL.

Generally, you use the URL (or, GET) when you want to allow linking. So, a specific product can be:

https://www.mycoolsite.com/products?ProdID=121

however, lets say you keep up with this, and you decide to keep using GET (or the URL) for adding stuff...

https://www.mycoolsite.com/products?ProdID=121&AddOns=1,2,3,5,6,9,10,11&ReferalSite=foo123&SomeOtherParam=areallylongurlencodedstringwith%20forspacesorpossibly+forspaceandalotofotherweirdstuff

that URL is far from pretty and annoying to remember. Sure, you can learn about URL rewrites and all the good stuff that makes a site scalable with a data driven back end, but that comes with practice and learning about how the technologies work. You could also "hide" a lot of that and make a POST through a form, and use hidden fields as necessary, etc...

In short - there is more than one way of doing things. Some are just more "right" for the job than others.

To repeat - you are doing nothing wrong.

All of us have our own idea of good development. In this particular case, I would side with diafol and actually store a user's activty in a database to keep track. It's much safer if the data is potentially going to give you money, and when you are dealing with other people's money you always want to keep things safe and secure. Abstracting personal data into a database, and keeping track of people's activities the same way, helps give a "state" to a stateless environment (i.e., the web).

Keep playing, keep learning, and keep asking questions :)

Ryan

ryandropp thanks alot for the help i will try to build this same thing with the post, and are you a teacher?, if you are your students are really lucky. becuase the way you explain things is really good. thanks
and i will go and start coding and if i run into problem i will post my problem here again, i am not marking this question as solved today i will do that tommorow, the reason is that may be hag++ and diafol might visit this again give me some advice as you did,

and more thing its not my idea to get the value from url, i was watching vedio on you tube, they did it that way so i did this way too, although i changed the code but the base remain same. vedio from phpmyacademy, can you suggest any good books for shopping cart? thanks

thanks for the help, i will follow your advice

<<<<<<<<<<<<<<<<
Keep playing, keep learning, and keep asking questions :)

Ryan

>

Member Avatar for diafol

OK, just to clear up the GET/POST issue. GET is used when you are not making changes to anything on the server, just GETting information. If you modify anything on the server with any form info, then use POST - this includes DBs and files. POST is not more secure than GET, other than it's more difficult to accidentally change the data structure (key/value pairs). Malicious users will be able to change anything on the page and send it to your server in a variety of ways - so always treat any input from the user as highly suspect.

With regard to my comment. If you are keeping a cart, then you need the stored data to be permanent somehow, otherwise an outage could cause outrage! So, you have a few options: traditional DB storage, cookies (not recommended), localStorage (client-side - so not generally available to server). As I satated earlier - if you make changes to something on the server, you SHOULD use POST.

Browsers usually resubmit form data on page refresh, so to avoid this forms should be sent to a formhandler file from which you're then redirected back to the original form page (or elsewhere). It's a bit more hassle, but you should never have the situation where refresh causes changes to your data.

thanks diafol for the reply, you guys really explain good, means you not only give the answer you also explain why you are saying this with reason, for the I am learning my self through you tube, can you suggest any good book which have good example specially for shopping cart

thanks for the time,

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.