A shopping cart in php will be a good example for learning. When I started using PHP, I began like most other people; the basics. I then promised to show you how to create a simple shopping cart. I have to warn you beforehand, this is not really a complex version. I figured it is smart to start with a simpler version then add more functionality to it as we proceed. So, let us get to it. I am going to do this in reverse, that is, show you snapshots of the cart then dissect the code. So, here we go!
Assuming you were looking for oil, spark plugs and tires for your good old truck, you would visit Crazy Auto Store and add them to the cart. As shown above, you enter the quantities into the input area. Simple right? Assuming you have done that, and hit ‘Submit Your Order’ button: Here is what you will see:
Yeah, when I said it was going to be simple, I meant it. Now let us take a look at both the HTML and PHP that made the above possible!
Shopping Cart In PHP : HTML FILE (store.html)
< !DOCTYPE html>
That is the html file (store.html). As you can see, I linked an external css file for presentation. Now that we have got that out of the way, we can look back at the first snapshot and see where it came from. Let us get the PHP file started.
PHP FILE (store.php)
< !DOCTYPE html>
Crazy Auto Store
Below is your order summary:
//declare the variables here
$oilqty = 0;
$sparksqty = 0;
$tiresqty = 0;
$total = 0;
//Now let us get the values from the form
$oilqty = &$_POST['oil'];
$sparksqty = &$_POST['sparks'];
$tiresqty = &$_POST['tires'];
$total = $oilqty + $sparksqty + $tiresqty;
echo 'You ordered on ‘. date(‘H:i, jS F Y’). ‘:’;
echo ‘ ‘.$oilqty. ‘ Oil Containers
echo ‘ ‘.$sparksqty. ‘ Spark Plugs ‘;
echo ‘ ‘.$tiresqty. ‘ New Tires
echo ‘ ‘.$total. ‘ Total Items ‘;
Copyright 2013 © Shopping Cart In PHP
Again, I used my own css here while creating this shopping cart in php. This should do it. That is all you need to accomplish what I showed you in the snapshots. Easy right? Just a brief explanation for the php file:
You might have noticed a couple of things: isset() and $_POST. I used the isset() method to check whether the values of (oil,sparks, tires) are set in the $_POST array. So I have already answered the ‘what is the $_POST’ thingy. When you click submit after filling up the form, the data you entered is stored in that $_POST array, that way, you can access them later and do some calculations or magic!
Next time, I will be building on top of what I did today, to add more functionality to our shopping cart in php! Think about shipping, discounts and more stuff! I hope to see you around and if you have any questions, please let me know and I will be glad to talk to you. Take care!
Please share this post if you liked it and let me know if you have any comments because I would love to hear from you! Please subscribe to more great posts!