Building a PHP Shopping Cart from scratch


First we can start with the database structure for this shopping cart.In this shopping cart we will be using four tables, ie  (products, customers, orders and order_detail ).

The structure of all these tables is shown below

Database Tables

Products    The products in this table will be shown to the user, Anyone can add these products to the shopping cart
Customers When the user places order, the billing detail will be stored in this table
Orders There will be a single entry for each successful order. Each order will be assigned a unique serial/order number.
Order Detail There will be a single entry for each item purchased. Although price is available from the products table, but if the price of an item changes in the products table, it should not be changed in the order_detail table. So these are two different fields.

Table Structure of shopping cart

For ‘products’

 


CREATE TABLE  products  (`serial` int(11) NOT NULL auto_increment,`name` varchar(20) NOT NULL,`description` varchar(255)   NOT NULL,`price` float NOT NULL,`picture` varchar(80) NOT NULL,PRIMARY KEY  (`serial`)) ENGINE=MyISAM ;

For ‘customers’

  


CREATE TABLE `customers` (`serial` int(11) NOT NULL auto_increment,`name` varchar(20) NOT NULL,`email` varchar(80) NOT NULL,`address` varchar(80) NOT NULL,`phone` varchar(20) NOT NULL, PRIMARY KEY  (`serial`)) ENGINE=MyISAM ;

For table ‘orders’

  


CREATE TABLE IF NOT EXISTS `orders` (`serial` int(11) NOT NULL auto_increment, `date` date NOT NULL, `customerid` int(11) NOT NULL,
 PRIMARY KEY  (`serial`)) ENGINE=MyISAM ;

For table ‘order_detail’

  


CREATE TABLE IF NOT EXISTS `order_detail` ( `orderid` int(11) NOT NULL, `productid` int(11) NOT NULL, `quantity` int(11) NOT NULL,
 `price` float NOT NULL) ENGINE=MyISAM;

Let’s now come to PHP. The shopping process will work like this:

  •  The user adds a product to his/her shopping cart
  •  The PHP script (products.php) receives this action and stores the requested product in the session array
  •  The PHP script redirects to a different page (shoppingcart.php) which displays purchased items to the user.

Creating a Product Page

After inserting product name and details into database, we need to create the product page as below.

 

Connecting to the Database

Before you can access data in a database, you must create a connection to the database.

In PHP, this is done with the mysql_connect() function.

@mysql_connect("localhost","username","password or die("please try again later");

@mysql_select_db("shopping") or die("Database not found J");
 

Displaying the Products

Before attempting this, be sure that you have created a table that contains some data. In this, we will output the first entry of our MySQL “products” table to the web browser.

$result=mysql_query("select * from products");                                           -- Run Mysql Query --

while($row=mysql_fetch_array($result)){                                                  -- Fetch array with while loop --

<!--?=$row['picture']? -->                                                                                                        -- Display the row --
<? }?>

Creating the Cart Page

Check whether the id and action is set or else set this into 1 and empty.

if (isset($_GET['id']))

$id=$_GET['id'];

else

$id=1;

if (isset($_GET['action']))

$action=$_GET['action'];

else

$action="empty";

Creating an action for the cart using Switch Statement

switch($action){

case "add":

if($_SESSION['cart'][$id])

$_SESSION['cart'][$id]++;

else

$_SESSION['cart'][$id]=1;

break;

case "remove":

if($_SESSION['cart'][$id])

{

$_SESSION['cart'][$id]--;

if($_SESSION['cart'][$id]==0)

unset($_SESSION['cart'][$id]);

}

break;

case "empty":

unset($_SESSION['cart']);

break;
}

Display the Cart

Displaying the cart using foreach loop. Foreach loops in PHP can be used to iterate over the contents of an array. They are commonly used for executing the same piece of code multiple times for different data values.


// Display cart 

if(isset($_SESSION['cart']))
{

echo "
<p style='margin-left:380px;' ><a style='color:#FFFF00; text-decoration:none'  href='product.php?id=".$id."&action=none' >Continue shopping</a><a href='billing.php'  style='color:#fff; text-decoration:none;margin-left:310px;' ><b>Place Order</b></a></p>

<table  style='padding:10px;'  align='center' border='0' bgcolor='F6F6F6' cellpadding='0' width='600'>";
$total=0;
foreach($_SESSION['cart'] as $id => $x)
{
include("common/db.php");
$result=mysql_query("select name,price from products WHERE serial=$id");
$myrow=mysql_fetch_array($result);
$name=$myrow['name'];
$price=$myrow['price'];
$line_cost=$price*$x;
$total= $total+$line_cost;

	echo "
<tr bgcolor='#f0f0f0'>";
	echo "
<td align='left'>$name</td>
";
	echo "
<td align='right'> $x <a href='cart.php?id=".$id."&action=remove' ><img src='images/s.png'/></a> <a href='cart.php?id=".$id."&action=add' ><img src='images/a.png'/></a></td>
";
	echo"
<td align='right'>=$line_cost</td>
";
	echo "</tr>
";
}
	echo"
<tr >";
	echo "
<td align='right'>
<b> Total </b></td>
";
	echo "
<td align='right'>
<b> $total </b></td>
";
	echo "</tr>
";
	echo "</table>
";
}
else
	echo"cart is Empty";

Billing Page for shopping cart

If the cart is not empty display the customer details form, else redirect it to products display page


if(isset($_SESSION['cart']) )

{

if(empty($_REQUEST['submit'])){

?></pre>
<div align="center">
<h1 style="color: #ff0;">Billing Info</h1>
<table style="padding: 20px;" border="0" bgcolor="F6F6F6">
<tbody>
<tr>
<td>Name</td>
<td><form id="form1" name="form1">
<label for="name"></label>

<input id="name" type="text" name="name" /></form></td>
</tr>
<tr>
<td>Email</td>
<td>
<label for="email"></label>

<input id="email" type="text" name="email" /></td>
</tr>
<tr>
<td>Address</td>
<td>
<label for="address"></label>

<textarea id="address" name="address" rows="5" cols="45"></textarea></td>
</tr>
<tr>
<td>Phone No</td>
<td>
<label for="phone"></label>

<input id="phone" type="text" name="phone" /></td>
</tr>
<tr>
<td></td>
<td><input id="submit" type="submit" name="submit" value="Submit" /></td>
</tr>
</tbody>
</table>
</div>
<pre><!--?php }}<br ?-->else

{

print "<script type="text/javascript">// <![CDATA[
"; print " self.location='product.php';"; print "
// ]]></script>"; } ?> 

Adding Data to a Database

The customer details and order details are stored inside the database.

<!--?php if(!empty($_REQUEST['submit'])) { $cname=$_REQUEST['name']; $email=$_REQUEST['email']; $address=$_REQUEST['address']; $phone=$_REQUEST['phone']; include("common/db.php"); $result=mysql_query("insert into customers values('','$cname','$email','$address','$phone')"); $customerid=mysql_insert_id(); $date=date('Y-m-d'); $result=mysql_query("insert into orders values('','$date','$customerid')"); $orderid=mysql_insert_id(); $total=0; foreach($_SESSION['cart'] as $id =--> $x)

{

include("common/db.php");

$result=mysql_query("select serial,name,price from products WHERE serial=$id");

$myrow=mysql_fetch_array($result);

$name=$myrow['name'];

$price=$myrow['price'];

$line_cost=$price*$x;

$total= $total+$line_cost;

mysql_query("insert into order_detail values ($orderid,$id,$x,$price)");

}

echo"<span style="color: #fff;">Thank you ".$cname." for placing an order

";

unset($_SESSION['cart']);

}

?>

In this tutorial I’m not including the payment gateway. Instead of that I am  storing the details of successful orders inside a database.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: