Wednesday, January 30, 2008

Shopping Cart Help

*******************Important URL for Coding ***********************
http://de.tikiwiki.org/xref-BRANCH-1-9/nav.html?lang/ca/language.php.source.html

********************************************************
Creating the Database

Let's assume that we're running a website that sells Sony Playstation 2 games. We'll need one table to store the details of each product, and another table to store the contents of each user's shopping cart, so that these details can persist over multiple sessions.

Fire up the MySQL console application and create a database named cart. Populate the database with two tables: items and cart, using this code:

create database cart;

create table items
(
itemId int auto_increment not null,
itemName varchar(50),
itemDesc varchar(250),
itemPrice decimal(4,2),
primary key(itemId),
unique id(itemId)
);

create table cart
(
cartId int auto_increment not null,
cookieId varchar(50),
itemId int,
qty int,
primary key(cartId),
unique id(cartId)

);

The first table, items, will contain a list of items that the user will be able to add to her cart. The items table contains four fields, as described below:

* itemId: A unique numeric identifier that labels each item with its own ID.
* itemName: The name of the item in the catalog.
* itemDesc: A short description of the item in the catalog.
* itemPrice: The price of the item, such as 45.99.

The cart table will store the details of each item in the users cart as she adds them. The cart table also contains four fields, which are described below:

* cartId: A unique numeric identifier that labels each item in the user's cart with an ID.
* cookieId: This is the most important field in both of the tables. It is used to persist the user's cart over multiple sessions. It is the value of the session ID with which the user first started browsing the range of products.
* itemId: The ID of the item that the user is purchasing.
* qty: The number (quantity) of this specific item being purchased.


Displaying the Items

Displaying the list of items from our items table is fairly easy. We'll display the items for sale on one page, and display the shopping cart on another page. We'll also create a file that will store the connection details of the database—along with two functions that will allow us to connect to and work with the database. Create a file called db.php (or open this file from the folder of sample files that you downloaded on the first page of this tutorial) and enter the following code into it:


// This page contains the connection routine for the
// database as well as getting the ID of the cart, etc.

$dbServer = "localhost";
$dbUser = "admin";
$dbPass = "password";
$dbName = "cart";

function ConnectToDb($server, $user, $pass, $database)
{
// Connect to the database and return
// true/false depending on whether or
// not a connection could be made.

$s = @mysql_connect($server, $user, $pass);
$d = @mysql_select_db($database, $s);

if(!$s || !$d)
return false;
else
return true;
}

function GetCartId()
{
// This function will generate an encrypted string and
// will set it as a cookie using set_cookie. This will
// also be used as the cookieId field in the cart table
if(isset($_COOKIE["cartId"]))
{
return $_COOKIE["cartId"];
}
else
{
// There is no cookie set. We will set the cookie
// and return the value of the users session ID

session_start();
setcookie("cartId", session_id(), time() + ((3600 * 24) * 30));
return session_id();
}
}

?>

First, we'll define four variables to hold the details of the MySQL database's server, username, password, and database name respectively. Next, we'll use the ConnectToDb function, which uses our database variables and connects to the MySQL database:

$s = @mysql_connect($server, $user, $pass);
$d = @mysql_select_db($database, $s);

if(!$s || !$d)
return false;
else

return true;

Notice how the calls to mysql_connect and mysql_select_db are prepended with the @ symbol. The @ symbol tells PHP not to produce any errors if the connect fails. If either of the connection or database selection functions fail, then ConnectToDb returns false. Otherwise it returns true, indicating a successful connection.

The GetCartId function makes use of one cookie variable to track a user across multiple sessions. It starts by checking if the cartId cookie variable is set. If not, it grabs the users session ID and sets it as a cookie value which expires in 30 days.

Note: The expiry date of the setcookie function is specified in seconds, so (3600 * 24) * 30 means 3600 seconds ( 1 hour) * 24 (1 day) * 30 (1 month).

The GetCartId function is used in combination with the MySQL cart table to track which user has added which items to their cart.

Db.php is included by both the item listing page and the cart. The item listing page is called products.php. It begins like this:


// This page will list all of the items
// from the items table. Each item will have
// a link to add it to the cart

include("db.php");

// Get a connection to the database
$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);
$result = mysql_query("select * from items order by itemName asc");

?>

As you can see, we include db.php and call the ConnectToDb function to attain a connection to our MySQL database. Next, we grab the entire list of items from the items table and store the result in the $result variable.

Each item will be displayed as part of a table. We'll output some HTML tags and the beginning row of our table before starting a loop through each item, like this:

while($row = mysql_fetch_array($result))
{
?>

For each item, we'll output its name, price, description, and a link to add it to that unique user's shopping cart:









$









Add Item



<<tr>






Finally, we'll close all the table and HTML tags, and display a link to the shopping cart, called cart.php (we'll create the cart.php file in the next section):




Your Shopping Cart >>








After loading up products.php in my browser, you'll receive the following page:
Figure 1. The products.php page displayed in a browser.

Figure 1.The products.php page displayed in a browser.

The "Add Item" link for each item links to cart.php. Now we're ready to create the cart.php page, which allows users to add, update, and delete items from the shopping cart.






Writing the cart.php Script

A shopping cart must perform four functions.

1. It must allow users to add and remove products from their cart.
2. It must allow users to change the quantity of items for each product in their cart.
3. It must allow users to see the products that exist in their cart.
4. It must allow users to see a cumulative total of all of the products in their cart.

Cart.php contains four functions that implement the requirements described above. Cart.php relies on a query string variable, named action, to tell it what to do:


include("db.php");

switch($_GET["action"])
{
case "add_item":
{
AddItem($_GET["id"], $_GET["qty"]);
ShowCart();
break;
}
case "update_item":
{
UpdateItem($_GET["id"], $_GET["qty"]);
ShowCart();
break;
}
case "remove_item":
{
RemoveItem($_GET["id"]);
ShowCart();
break;
}
default:
{
ShowCart();
}
}
?>

The script above uses the $_GET associative array, which was introduced with PHP version 4.1, and was made standard with PHP version 4.2. In PHP 4.2, $HTTP_GET_VARS is deprecated—so you should get into the habit of using $_GET and $_POST instead of $HTTP_GET_VARS and $HTTP_POST_VARS. Using $_GET is quicker too, because it is automatically globally scoped, whereas $HTTP_GET_VARS is not.

Looking at the switch statement above, we have four possible cases. These cases are discussed below:

* add_item: When the user clicks on the "Add Item" button for an item listed on the products.php page, this case is called. It calls the AddItem function, which passed the details of the item's ID number and quantity.
* update_item: This updates the quantity of an item placed in the user's shopping cart. As you will soon see, each item in the cart is displayed with a pop-up list, that, when changed, automatically updates the number of a specific item in the users shopping cart.
* remove_item: This deletes an item from the cart table for the current user.

If the cart.php page is called with no query string parameters, then the ShowCart function is called. Let's start by looking at the AddItem function.

AddItem accepts two parameters: The ID of the item to add to the cart and the quantity (numeric value) for each item that will be purchased:

function AddItem($itemId, $qty)

The main part of the AddItem function checks whether or not this item already exists in the users cart. If it does exist, then the item's quantity field is updated and it isn't added again:

$result = mysql_query("select count(*) from cart where cookieId = '" . GetCartId() . "' and itemId = $itemId");

$row = mysql_fetch_row($result);
$numRows = $row[0];

if($numRows == 0)
{
// This item doesn't exist in the users cart,
// we will add it with an insert query

@mysql_query("insert into cart(cookieId, itemId, qty) values('" . GetCartId() . "', $itemId, $qty)");
}
else
{
// This item already exists in the users cart,
// we will update it instead

UpdateItem($itemId, $qty);
}

Looking at the code above, we can see that if $numRows equals zero (in other words, if the item isn't already in the users cart) then the item is added to the cart table. If not, the items quantity field is updated by calling the UpdateItem function, which is described below.

UpdateItem accepts two parameters, in the same way that the AddItem function does:

function UpdateItem($itemId, $qty)

It executes a simple UPDATE SQL query against the cart table, updating the quantity of one specific item. The cookieId field is used to match the users session ID to that particular product, making sure that the quantity is only updated for that item and the current user:

mysql_query("update cart set qty = $qty where cookieId = '" . GetCartId() . "' and itemId = $itemId");

Removing an item is a simple matter of calling the RemoveItem function. The RemoveItem function accepts only one parameter: the ID of the item to delete:

function RemoveItem($itemId)

Once we've connected to the database, a simple SQL DELETE query removes the item from the current users cart:

mysql_query("delete from cart where cookieId = '" . GetCartId() . "' and itemId = $itemId");

All of these functions are good, but to actually call them, we need to look at the ShowCart function. We'll examine it in the next section of this tutorial.







**************** db.php file ********************************

<?php



// This page contains the connection routine for the

// database as well as getting the ID of the cart, etc



$dbServer = "localhost";

$dbUser = "root";

$dbPass = "";

$dbName = "cart";



function ConnectToDb($server, $user, $pass, $database)

{

// Connect to the database and return

// true/false depending on whether or

// not a connection could be made.



$s = @mysql_connect($server, $user, $pass);

$d = @mysql_select_db($database, $s);



if(!$s || !$d)

return false;

else

return true;

}



function GetCartId()

{

// This function will generate an encrypted string and

// will set it as a cookie using set_cookie. This will

// also be used as the cookieId field in the cart table



if(isset($_COOKIE["cartId"]))

{

return $_COOKIE["cartId"];

}

else

{

// There is no cookie set. We will set the cookie

// and return the value of the users session ID



session_start();

setcookie("cartId", session_id(), time() + ((3600 * 24) * 30));

return session_id();

}

}



?>





**********************************cart.php *************************

<?php



include("db.php");



switch($_GET["action"])

{

case "add_item":

{

AddItem($_GET["id"], $_GET["qty"]);



ShowCart();

break;

}

case "update_item":

{

UpdateItem($_GET["id"], $_GET["qty"]);

ShowCart();

break;

}

case "remove_item":

{

RemoveItem($_GET["id"]);

ShowCart();

break;

}

default:

{

ShowCart();

}

}



function AddItem($itemId, $qty)

{

// Will check whether or not this item

// already exists in the cart table.

// If it does, the UpdateItem function

// will be called instead



global $dbServer, $dbUser, $dbPass, $dbName;



// Get a connection to the database

$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);



// Check if this item already exists in the users cart table

$result = mysql_query("select count(*) from cart where cookieId = '" . GetCartId()
. "' and itemId = $itemId");

$row = mysql_fetch_row($result) or die("failed to execute query");

$numRows = $row[0];



if($numRows == 0)

{

// This item doesn't exist in the users cart,

// we will add it with an insert query



@mysql_query("insert into cart(cookieId, itemId, qty) values('" . GetCartId() .
"', $itemId, $qty)");

}

else

{

// This item already exists in the users cart,

// we will update it instead



UpdateItem($itemId, $qty);

}

}



function UpdateItem($itemId, $qty)

{

// Updates the quantity of an item in the users cart.

// If the qutnaity is zero, then RemoveItem will be

// called instead



global $dbServer, $dbUser, $dbPass, $dbName;



// Get a connection to the database

$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);



if($qty == 0)

{

// Remove the item from the users cart

RemoveItem($itemId);

}

else

{

mysql_query("update cart set qty = $qty where cookieId = '" . GetCartId() . "'
and itemId = $itemId");

}

}



function RemoveItem($itemId)

{

// Uses an SQL delete statement to remove an item from

// the users cart



global $dbServer, $dbUser, $dbPass, $dbName;



// Get a connection to the database

$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);



mysql_query("delete from cart where cookieId = '" . GetCartId() . "' and itemId
= $itemId");

}



function ShowCart()

{

// Gets each item from the cart table and display them in

// a tabulated format, as well as a final total for the cart



global $dbServer, $dbUser, $dbPass, $dbName;



// Get a connection to the database

$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);



$totalCost = 0;

$result = mysql_query("select * from cart inner join items on cart.itemId =
items.itemId where cart.cookieId = '" . GetCartId() . "' order by items.itemName
asc");

?>

<html>

<head>

<title> Your Shopping Cart </title>

<script language="JavaScript">



function UpdateQty(item)

{

itemId = item.name;

newQty = item.options[item.selectedIndex].text;



document.location.href = 'cart.php?action=update_item&id='+itemId+'&qty='+newQty;

}



</script>

</head>

<body bgcolor="#ffffff">

<h1>Your Shopping Cart</h1>

<form name="frmCart" method="get">

<table width="100%" cellspacing="0" cellpadding="0" border="0">

<tr>

<td width="15%" height="25" bgcolor="red">

<font face="verdana" size="1" color="white">

&nbsp;&nbsp;<b>Qty</b>

</font>

</td>

<td width="55%" height="25" bgcolor="red">

<font face="verdana" size="1" color="white">

<b>Product</b>

</font>

</td>

<td width="20%" height="25" bgcolor="red">

<font face="verdana" size="1" color="white">

<b>Price Each</b>

</font>

</td>

<td width="10%" height="25" bgcolor="red">

<font face="verdana" size="1" color="white">

<b>Remove?</b>

</font>

</td>

</tr>

<?php



while($row = mysql_fetch_array($result))

{

// Increment the total cost of all items

$totalCost += ($row["qty"] * $row["itemPrice"]);

?>

<tr>

<td width="15%" height="25">

<font face="verdana" size="1" color="black">

<select name="<?php echo $row["itemId"]; ?>" onChange="UpdateQty(this)">

<?php



for($i = 1; $i <= 20; $i++)

{

echo "<option ";

if($row["qty"] == $i)

{

echo " SELECTED ";

}

echo ">" . $i . "</option>";

}

?>

</select>

</font>

</td>

<td width="55%" height="25">

<font face="verdana" size="1" color="black">

<?php echo $row["itemName"]; ?>

</font>

</td>

<td width="20%" height="25">

<font face="verdana" size="1" color="black">

$<?php echo number_format($row["itemPrice"], 2, ".", ","); ?>

</font>

</td>

<td width="10%" height="25">

<font face="verdana" size="1" color="black">

<a href="cart.php?action=remove_item&id=<?php echo $row["itemId"];
?>">Remove</a>

</font>

</td>

</tr>

<?php

}



// Display the total

?>

<tr>

<td width="100%" colspan="4">

<hr size="1" color="red" NOSHADE>

</td>

</tr>

<tr>

<td width="70%" colspan="2">

<font face="verdana" size="1" color="black">

<a href="products.php">&lt;&lt; Keep Shopping</a>

</font>

</td>

<td width="30%" colspan="2">

<font face="verdana" size="2" color="black">

<b>Total: $<?php echo number_format($totalCost, 2, ".", ","); ?></b>

</font>

</td>

</tr>

</table>

</form>

</body>

</html>

<?php

}



?>




********************************products.php ********************************

<?php



// This page will list all of the items

// from the items table. Each item will have

// a link to add it to the cart



include("db.php");



// Get a connection to the database

$cxn = @ConnectToDb($dbServer, $dbUser, $dbPass, $dbName);

$result = mysql_query("select * from items order by itemName asc");

?>

<html>

<head>

<title> Product List </title>

</head>

<body bgcolor="#ffffff">

<h1>Products</h1>

<table width="100%" cellspacing="0" cellpadding="0" border="0">

<tr>

<td width="30%" height="25" bgcolor="red">

<font face="verdana" size="1" color="white">

&nbsp;&nbsp;<b>Product</b>

</font>

</td>

<td width="10%" height="25" bgcolor="red">

<font face="verdana" size="1" color="white">

<b>Price</b>

</font>

</td>

<td width="50%" height="25" bgcolor="red">

<font face="verdana" size="1" color="white">

<b>Description</b>

</font>

</td>

<td width="10%" height="25" bgcolor="red">

<font face="verdana" size="1" color="white">

<b>Add</b>

</font>

</td>

</tr>

<?php

while($row = mysql_fetch_array($result))

{

?>

<tr>

<td width="30%" height="25">

<font face="verdana" size="1" color="black">

<?php echo $row["itemName"]; ?>

</font>

</td>

<td width="10%" height="25">

<font face="verdana" size="1" color="black">

$<?php echo $row["itemPrice"]; ?>

</font>

</td>

<td width="50%" height="25">

<font face="verdana" size="1" color="black">

<?php echo $row["itemDesc"]; ?>

</font>

</td>

<td width="10%" height="25">

<font face="verdana" size="1" color="black">

<a href="cart.php?action=add_item&id=<?php echo $row["itemId"]; ?>&qty=1">Add
Item</a>

</font>

</td>

</tr>

<tr>

<td width="100%" colspan="4">

<hr size="1" color="red" NOSHADE>

</td>

</tr>

<?php

}

?>

<tr>

<td width="100%" colspan="4">

<font face="verdana" size="1" color="black">

<a href="cart.php">Your Shopping Cart &gt;&gt;</a>

</font>

</td>

</tr>

</table>

</body>

</html>



**************************

No comments: