Build a shopping cart with php part-2

After Completing Build a shopping cart with php part-1, now we learn in this series part 2, Here we learn how to add items to the cart, How to display our Basket Summary , How delete items from our cart and how to connect our shopping with paypal payment gateway..

Adding the Item to the Cart

The purpose of addtobasket.php is to add the selected item to the orderitems table and then redirect to a page that summarizes the items in the shopping cart.

The addtobasket.php page is quite a large script with lots of nested if statements. This makes it fairly difficult to break down and discuss piece by piece, as has been done with most other scripts. To make this easier to understand, add the entire code to the file. You’ll run through it step by step at the end.

Create addtobasket.php and add the code:


<?php

session_start();

require("config.php");

require("functions.php");

$validid = pf_validate_number($_GET['id'],"redirect", $config_basedir);

$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";

$prodres = mysql_query($prodsql);

$numrows = mysql_num_rows($prodres);

$prodrow = mysql_fetch_assoc($prodres);

if($numrows == 0)

{

header("Location: " . $config_basedir);

}

else

{

if($_POST['submit'])

{

if($_SESSION['SESS_ORDERNUM'])

{

$itemsql = "INSERT INTO orderitems(order_id,product_id, quantity)
VALUES(". $_SESSION['SESS_ORDERNUM'] . ", ". $_GET['id'] . ", ". $_POST['amountBox'] . ")";

mysql_query($itemsql);

}

else

{

if($_SESSION['SESS_LOGGEDIN'])

{

$sql = "INSERT INTO orders(customer_id,registered, date)
VALUES(". $_SESSION['SESS_USERID'] . ", 1, NOW())";

mysql_query($sql);

session_register("SESS_ORDERNUM");

$_SESSION['SESS_ORDERNUM'] = mysql_insert_id();

$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity)
VALUES(". $_SESSION['SESS_ORDERNUM']. ", " . $_GET['id'] . ", ". $_POST['amountBox'] . ")";

mysql_query($itemsql);

}

else

{

$sql = "INSERT INTO orders(registered,date, session)
VALUES(". "0, NOW(), '" . session_id() . "')";

mysql_query($sql);

session_register("SESS_ORDERNUM");

$_SESSION['SESS_ORDERNUM'] = mysql_insert_id();

$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity)
VALUES(". $_SESSION['SESS_ORDERNUM'] . ", " . $_GET['id'] . ", ". $_POST['amountBox'] . ")";

mysql_query($itemsql);

}

}

$totalprice = $prodrow['price'] * $_POST['amountBox'] ;

$updsql = "UPDATE orders SET total = total + ". $totalprice . " WHERE id = ". $_SESSION['SESS_ORDERNUM'] . ";";

mysql_query($updres);

header("Location: " . $config_basedir . "showcart.php");

}

else

{

require("header.php");

echo "<form action='addtobasket.php?id=". $_GET['id'] . "' method='POST'>";

echo "<table cellpadding='10'>";

echo "<tr>";

if(empty($prodrow['image'])) {

echo "<td><imgsrc='./productimages/dummy.jpg' width='50' alt='". $prodrow['name'] . "'></td>";

}

else {

echo "<td>

<img src='./productimages/" . $prodrow['image']. "' width='50' alt='" . $prodrow['name']. "'></td>";

}

echo "<td>" . $prodrow['name'] . "</td>";

echo "<td>Select Quantity <select name='amountBox'>";

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

{

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

}

echo "</select></td>";

echo "<td><strong>&pound;". sprintf('%.2f', $prodrow['price']) . "</strong></td>";

echo "<td><input type='submit'

name='submit' value='Add to basket'></td>";

echo "</tr>";

echo "</table>";

echo "</form>";

}

}

require("footer.php");

?>

To best explain this code, review the following bulleted points to see what happens. As you read each bullet, reference the code you typed into your editor. All set? Here goes…

■ At the top of the page, a query returns the product with the id GET variable. If no rows are returned, the page redirects to the site’s base URL.

■ The form is displayed and includes a drop-down select box that uses a for loop to provide options from 1 to 100. In addition to the form, some product information is displayed.

■ When the user submits the form, the page is reloaded and a check is made to see if a SESS_ORDERNUM variable exists. If it does, this means an order is already open and an INSERT statement adds the product id and quantity to the orderitems table, in which the order_id is SESS_ORDERNUM.

■ If no SESS_ORDERNUM exists, an order must be created in the orders table before you can add the item to the orderitems table. A check is then made to see if the SESS_LOGGEDIN session variable exists. If it does, the user is already logged in and an order is created before the item is added to the orderitems table. If SESS_LOGGEDIN does not exist, the user is not currently logged in (they possibly don’t have a user account). As such, an order is created in the orders table (using session_id() to get the unique session id) and then the item is added to the orderitems table.

■ The total field in the orders table is updated. This is performed by calculating the price multiplied by the quantity (the result is stored in $totalprice).

■ Finally, the page redirects to the cart summary page on showcart.php.

Before you click the Submit button, make sure your page looks similar to the one shown in Figure 6.

php shopping cart basket

Displaying the Basket Summary

When the addtobasket.php script has finished processing, the page redirects to showcart.php. This page provides a summary of the items added to the shopping cart.

Occasionally, you might need to display a summary of the items. To prevent duplication of code, a function called showcart() has been created to display the summary. Before you look at the function, create a new file called showcart.php and add the following code, which uses the showcart() function:


<?php

session_start();

require("header.php");

require("functions.php");

echo "<h1>Your shopping cart</h1>";

showcart();

if(isset($_SESSION['SESS_ORDERNUM']) == TRUE) {

$sql = "SELECT * FROM orderitems WHERE order_id = " . $_SESSION['SESS_ORDERNUM'] . ";";

$result = mysql_query($sql);

$numrows = mysql_num_rows($result);

if($numrows >= 1) {

echo "<h2><a href='checkout-address.php'>Go to the checkout</a></h2>";

}

}

require("footer.php");

?>

The showcart() function does not include a link to the checkout, because not every page needs one. The block of code after the function call checks if an order number is available and if so, a check is made to see if the cart contains any items.

If the cart contains one or more items, the checkout link is displayed.

Add the showcart() code to functions.php:


<?php

function pf_validate_number($value, $function, $redirect) {

if(isset($value) == TRUE) {

if(is_numeric($value) == FALSE) {

$error = 1;

}

if($error == 1) {

header("Location: " . $redirect);

}

else {

$final = $value;

}

}

else {

if($function == 'redirect') {

header("Location: " . $redirect);

}

if($function == "value") {

$final = 0;

}

}

return $final;

}

function showcart()

{

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

{

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

{

$custsql = "SELECT id, status from orders WHERE customer_id = ". $_SESSION['SESS_USERID']. " AND status < 2;";

$custres = mysql_query($custsql);

$custrow = mysql_fetch_assoc($custres);

$itemssql = "SELECT products.*, orderitems.*, orderitems.id AS itemid FROM products, orderitems WHERE orderitems.product_id =products.id AND order_id = " . $custrow['id'];

$itemsres = mysql_query($itemssql);

$itemnumrows = mysql_num_rows($itemsres);

}

else

{

$custsql = "SELECT id, status from orders WHERE session = '" . session_id(). "' AND status < 2;";

$custres = mysql_query($custsql);

$custrow = mysql_fetch_assoc($custres);

$itemssql = "SELECT products.*, orderitems.*, orderitems.id AS itemid FROM products, orderitems WHERE orderitems.product_id = products.id AND order_id = " . $custrow['id'];

$itemsres = mysql_query($itemssql);

$itemnumrows = mysql_num_rows($itemsres);

}

}

else

{

$itemnumrows = 0;

}

if($itemnumrows == 0)

{

echo "You have not added anything to your shopping cart yet.";

}

else

{

echo "<table cellpadding='10'>";

echo "<tr>";

echo "<td></td>";

echo "<td><strong>Item</strong></td>";

echo "<td><strong>Quantity</strong></td>";

echo "<td><strong>Unit Price</strong></td>";

echo "<td><strong>Total Price</strong></td>";

echo "<td></td>";

echo "</tr>";

while($itemsrow = mysql_fetch_assoc($itemsres))

{

$quantitytotal =

$itemsrow['price'] * $itemsrow['quantity'];

echo "<tr>";

if(empty($itemsrow['image'])) {

echo "<td><img src='productimages/dummy.jpg' width='50' alt='" . $itemsrow['name'] . "'></td>";

}

else {

echo "<td><img src='productimages/" .$itemsrow['image'] . "' width='50' alt='". $itemsrow['name'] . "'></td>";

}

echo "<td>" . $itemsrow['name'] . "</td>";

echo "<td>" . $itemsrow['quantity'] . "</td>";

echo "<td><strong>&pound;" . sprintf('%.2f', $itemsrow['price']) . "</strong></td>";

echo "<td><strong>&pound;". sprintf('%.2f', $quantitytotal) . "</strong></td>";

echo "<td>[<a href='delete.php?id=". $itemsrow['itemid'] . "'>X</a>]</td>";

echo "</tr>";

@$total = $total + $quantitytotal;

$totalsql = "UPDATE orders SET total = ". $total . " WHERE id = ". $_SESSION['SESS_ORDERNUM'];

$totalres = mysql_query($totalsql);

}

echo "<tr>";

echo "<td></td>";

echo "<td></td>";

echo "<td></td>";

echo "<td>TOTAL</td>";

echo "<td><strong>&pound;". sprintf('%.2f', $total) . "</strong></td>";

echo "<td></td>";

echo "</tr>";

echo "</table>";

echo "<p><a href='checkout-address.php'>Go to the checkout</a></p>";

}

}

?>

Now we explain showcart() function code:


function showcart()

{

if($_SESSION['SESS_ORDERNUM'])

{

if($_SESSION['SESS_LOGGEDIN'])

{

$custsql = "SELECT id, status from orders WHERE customer_id = ". $_SESSION['SESS_USERID']. " AND status < 2;";

$custres = mysql_query($custsql);

$custrow = mysql_fetch_assoc($custres);

The outer if check in the function determines if an order number exists. If it does, a second if checks if the user is logged in. If this is the case, the query selects the row from the orders table that has the user id for the user and in which the status is 0 or 1. The query should return a single row only.

The main query to grab the item details is now ready to run:


$itemssql = "SELECT products.*, orderitems.*, orderitems.id AS itemid FROM products, orderitems WHERE orderitems.product_id =products.id AND order_id = " . $custrow['id'];

$itemsres = mysql_query($itemssql);

$itemnumrows = mysql_num_rows($itemsres);

}

If no user is logged in, a similar SELECT query is made to get the order number,but the match is made on the current session id. After this query, the list of items is returned:


else

{

$custsql = "SELECT id, status from orders WHERE session = '" . session_id() . "' AND status < 2;";

$custres = mysql_query($custsql);

$custrow = mysql_fetch_assoc($custres);

$itemssql = "SELECT products.*,orderitems.*, orderitems.id AS itemid FROM products, orderitems WHERE orderitems.product_id = products.id AND order_id = " . $custrow['id'];

$itemsres = mysql_query($itemssql);

$itemnumrows = mysql_num_rows($itemsres);

If no SESS_ORDERNUM variable is available, the $itemnumrows variable is set to 0:

}

}

else

{

$itemnumrows = 0;

}

This code checks $itemnumrows to see what value it contains. If the value is 0, a message displays to indicate the cart is empty:

if($itemnumrows == 0)

{

echo "You have not added anything to your shopping cart yet.";

}

If $itemnumrows has a value, the items are displayed:

else

{

echo "<table cellpadding='10'>";

echo "<tr>";

echo "<td></td>";

echo "<td><strong>Item</strong></td>";

echo "<td><strong>Quantity</strong></td>";

echo "<td><strong>Unit Price</strong></td>";

echo "<td><strong>Total Price</strong></td>";

echo "<td></td>";

echo "</tr>";

while($itemsrow = mysql_fetch_assoc($itemsres))

{

$quantitytotal =

$itemsrow['price'] * $itemsrow['quantity'];

echo "<tr>";

if(empty($itemsrow['image'])) {

echo "<td><img

src='./productimages/dummy.jpg' width='50' alt='". $itemsrow['name'] . "'></td>";

}

else {

echo "<td><img src='./productimages/" .$itemsrow['image'] . "' width='50' alt='". $itemsrow['name'] . "'></td>";

}

echo "<td>" . $itemsrow['name'] . "</td>";

echo "<td>" . $itemsrow['quantity'] . "</td>";

echo "<td><strong>&pound;". sprintf('%.2f', $itemsrow['price']). "</strong></td>";

echo "<td><strong>&pound;". sprintf('%.2f', $quantitytotal) . "</strong></td>";

echo "<td>[<a href='". $config_basedir . "delete.php?id=". $itemsrow['itemid'] . "'>X</a>]</td>";

echo "</tr>";

@$total = $total + $quantitytotal;

$totalsql = "UPDATE orders SET total = ". $total . " WHERE id = ". $_SESSION['SESS_ORDERNUM'];

$totalres = mysql_query($totalsql);

}

echo "<tr>";

echo "<td></td>";

echo "<td></td>";

echo "<td></td>";

echo "<td>TOTAL</td>";

echo "<td><strong>&pound;"

. sprintf('%.2f', $total) . "</strong></td>";

echo "<td></td>";

echo "</tr>";

echo "</table>";

echo "<p><a href='checkout-address.php'>Go to the checkout</a></p>";

}

}

After Submitting the Add to basket button our shopping cart look like:

Displaying shopping cart summery using php

Deleting Items

The showcart() function contains a link to delete.php, in which you can remove an item from the shopping cart. By clicking the link, the item is removed from the orderitems table, and the total price in the orders table is updated.

Create delete.php and begin adding the code:


<?php

require("config.php");

require('header.php');

$itemsql = "SELECT * FROM orderitems WHERE id = ". $_GET['id'] . ";";

$itemres = mysql_query($itemsql) or die(mysql_error());

$numrows = mysql_num_rows($itemres);

if($numrows == 0) {

header("Location: showcart.php");

}

$itemrow = mysql_fetch_assoc($itemres);

$prodsql = "SELECT price FROM products WHERE id = " . $itemrow['product_id'] . ";";

$prodres = mysql_query($prodsql)or die(mysql_error());;

$prodrow = mysql_fetch_assoc($prodres);

$sql = "DELETE FROM orderitems WHERE id = " . $_GET['id'];

$del=mysql_query($sql)or die(mysql_error());;

if($del){

header("Location: showcart.php");

}

require('footer.php');

?>

Now we explain delete.php file code


<?php

require("config.php");

require('header.php');

$itemsql = "SELECT * FROM orderitems WHERE id = ". $_GET['id'] . ";";

$itemres = mysql_query($itemsql) or die(mysql_error());

$numrows = mysql_num_rows($itemres);

if($numrows == 0) {

header("Location: showcart.php");

}

$itemrow = mysql_fetch_assoc($itemres);

In this code, the query pulls the item from the orderitems table, and the number of rows returned is checked. This check prevents someone modifying the URL and adding delete.php?id=73 if there is no item with an id of 73. If no rows are returned, a header redirect jumps to showcart.php. If a row is returned, the script continues:


$prodsql = "SELECT price FROM products

WHERE id = " . $itemrow['product_id'] . ";";

$prodres = mysql_query($prodsql);

$prodrow = mysql_fetch_assoc($prodres); $sql = "DELETE FROM orderitems WHERE id = " . $_GET['id'];

mysql_query($sql);

In this block, the price of the product is selected first and then a separate query removes the item from orderitems.

CHECKING IT OUT

After the user has finished adding items to his shopping cart, the checkout process can begin. This process involves two steps:

■ Prompt the user for a delivery address. If the user is already logged in, he should be asked if he wants to use the address he registered or use a different address. All addresses should be validated.

■ Prompt the user to choose a payment method, either PayPal or a check.

Create checkout-address.php and add the following code:


<?php

session_start();

require("config.php");

$statussql = "SELECT status FROM orders WHERE id = " .$_SESSION['SESS_ORDERNUM'];

$statusres = mysql_query($statussql);

$statusrow = mysql_fetch_assoc($statusres);

$status = $statusrow['status'];

if($status == 1) {

header("Location: " . $config_basedir . "checkout-pay.php");

}

if($status >= 2) {

header("Location: " . $config_basedir);

}

if($_POST['submit'])

{

if($_SESSION['SESS_LOGGEDIN'])

{

if($_POST['addselecBox'] == 2)

{

if(empty($_POST['forenameBox']) ||

empty($_POST['surnameBox']) ||

empty($_POST['add1Box']) ||

empty($_POST['add2Box']) ||

empty($_POST['add3Box']) ||

empty($_POST['postcodeBox']) ||

empty($_POST['phoneBox']) ||

empty($_POST['emailBox']))

{

header("Location: " . $basedir . "checkoutaddress.php?error=1");

exit;

}

$addsql = "INSERT INTO delivery_addresses(forename, surname, add1, add2, add3, postcode, phone, email)VALUES('" . strip_tags(addslashes( $_POST['forenameBox'])) . "', '" . strip_tags(addslashes( $_POST['surnameBox'])) . "', '" . strip_tags(addslashes( $_POST['add1Box'])) . "', '" . strip_tags(addslashes( $_POST['add2Box'])) . "', '" . strip_tags(addslashes( $_POST['add3Box'])) . "', '" . strip_tags(addslashes( $_POST['postcodeBox'])) . "', '" . strip_tags(addslashes(

$_POST['phoneBox'])) . "', '" . strip_tags(addslashes($_POST['emailBox'])) . "')";

mysql_query($addsql);

$setaddsql = "UPDATE orders SET delivery_add_id = " . mysql_insert_id() . ", status = 1 WHERE id = " . $_SESSION['SESS_ORDERNUM'];

mysql_query($setaddsql);

header("Location: " . $config_basedir . "checkout-pay.php");

}

else

{

$custsql = "UPDATE orders SET delivery_add_id = 0, status = 1 WHERE id = " . $_SESSION['SESS_ORDERNUM'];

mysql_query($custsql);

header("Location: " . $config_basedir . "checkout-pay.php");

}

}

else

{

if(empty($_POST['forenameBox']) ||

empty($_POST['surnameBox']) ||

empty($_POST['add1Box']) ||

empty($_POST['add2Box']) ||

empty($_POST['add3Box']) ||

empty($_POST['postcodeBox']) ||

empty($_POST['phoneBox']) ||

empty($_POST['emailBox']))

{

header("Location: " . "checkout-address.php?error=1");

exit;

}

$addsql = "INSERT INTO delivery_addresses(forename, surname, add1, add2, add3, postcode, phone, email) VALUES('" . $_POST['forenameBox'] . "', '" . $_POST['surnameBox'] . "', '" . $_POST['add1Box'] . "', '" . $_POST['add2Box'] . "', '" . $_POST['add3Box'] . "', '" . $_POST['postcodeBox'] . "', '" . $_POST['phoneBox'] . "', '" . $_POST['emailBox'] . "')";

mysql_query($addsql);

$setaddsql = "UPDATE orders SET delivery_add_id = " . mysql_insert_id() . ", status = 1 WHERE session = '" . session_id() . "'";

mysql_query($setaddsql);

header("Location: " . $config_basedir . "checkout-pay.php");

}

}

else

{

require("header.php");

echo "<h1>Add a delivery address</h1>";

if(isset($_GET['error']) == TRUE) {

echo "<strong>Please fill in the missing

information from the form</strong>";

}

echo "<form action='".$_SERVER['SCRIPT_NAME'] . "' method='POST'>";

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

{

?>

<input type="radio" name="addselecBox" value="1" checked>Use the address from my account</input><br>

<input type="radio" name="addselecBox"

value="2">Use the address below:</input>

<?php

}

?>

<table>

<tr>

<td>Forename</td>

<td><input type="text" name="forenameBox"></td>

</tr>

<tr>

<td>Surname</td>

<td><input type="text" name="surnameBox"></td>

</tr>

<tr>

<td>House Number, Street</td>

<td><input type="text" name="add1Box"></td>

</tr>

<tr>

<td>Town/City</td>

<td><input type="text" name="add2Box"></td>

</tr>

<tr>

<td>County</td>

<td><input type="text" name="add3Box"></td>

</tr>

<tr>

<td>Postcode</td>

<td><input type="text" name="postcodeBox"></td>

</tr>

<tr>

<td>Phone</td>

<td><input type="text" name="phoneBox"></td>

</tr>

<tr>

<td>Email</td>

<td><input type="text" name="emailBox"></td>

</tr>

<tr>

<td></td>

<td><input type="submit" name="submit" value="Add Address (press only once)"></td>

</tr>

</table>

</form>

<?php

}

require("footer.php");

?>

Now we explain the code step by step:


require("header.php");

echo "<h1>Add a delivery address</h1>";

if(isset($_GET['error']) == TRUE) {

echo "<strong>Please fill in the missinginformation from the form</strong>";

}

echo "<form action='" . $SCRIPT_NAME . "' method='POST'>";

if($_SESSION['SESS_LOGGEDIN'])

{

?>

<input type="radio" name="addselecBox" value="1" checked>Use the address from my

account</input><br>

<input type="radio" name="addselecBox"

value="2">Use the address below:</input>

<?php

}

?>

<table>

<tr>

<td>Forename</td>

<td><input type="text" name="forenameBox"></td>

</tr>

<tr>

<td>Surname</td>

<td><input type="text" name="surnameBox"></td>

</tr>

<tr>

<td>House Number, Street</td>

<td><input type="text" name="add1Box"></td>

</tr>

<tr>

<td>Town/City</td>

<td><input type="text" name="add2Box"></td>

</tr>

<tr>

<td>County</td>

<td><input type="text" name="add3Box"></td>

</tr>

<tr>

<td>Postcode</td>

<td><input type="text" name="postcodeBox"></td>

</tr>

<tr>

<td>Phone</td>

<td><input type="text" name="phoneBox"></td>

</tr>

<tr>

<td>Email</td>

<td><input type="text" name="emailBox"></td>

</tr>

<tr>

<td></td>

<td><input type="submit" name="submit"

value="Add Address (press only once)"></td>

</tr>

</table>

</form>

Before the form is displayed, an if checks if an error GET variable exists. If it does, an error message is displayed. The script then checks if the user is logged in, and if so, two radio buttons are added so that the user can choose between the address he registered and a different address. Move to the start of the file and add the following code:


<?php

session_start();

require("db.php");

$statussql = "SELECT status FROM orders WHERE id = ".$_SESSION['SESS_ORDERNUM'];

$statusres = mysql_query($statussql);

$statusrow = mysql_fetch_assoc($statusres);

$status = $statusrow['status'];

The first step is to determine the current status of the order. If the user has already been through the address stage of the checkout process, redirect the page to the payment screen. Obtain the status by searching for a record in the orders table that matches SESS_ORDERNUM. Then, set the $status variable to the correct status.

Note:

0 The user is still adding items to her shopping cart.
1 The user has entered her address.
2 The user has paid for the item.
10 The administrator has confirmed the transaction and sent the item.

If the status is set to 1, the user has already entered an address and the page redirects to the payment screen. If the status is 2 or higher, the order has been completed.

Redirect the page to the base URL of the site:


if($status == 1) {

header(“Location: “ . $config_basedir . “checkout-pay.php”);

}

if($status >= 2) {

header(“Location: “ . $config_basedir);

}

Begin processing the form:

if($status >= 2) {

header("Location: " . $config_basedir);

}

if($_POST[‘submit’])

{

if($_SESSION[‘SESS_LOGGEDIN’])

{

if($_POST[‘addselecBox’] == 2)

{

if(empty($_POST[‘forenameBox’]) ||

empty($_POST[‘surnameBox’]) ||

empty($_POST[‘add1Box’]) ||

empty($_POST[‘add2Box’]) ||

empty($_POST[‘add3Box’]) ||

empty($_POST[‘postcodeBox’]) ||

empty($_POST[‘phoneBox’]) ||

empty($_POST[‘emailBox’]))

{

header(“Location: “ . $basedir . “checkoutaddress.

php?error=1”);

exit;

}

The first nested if checks if the user is logged in. A check is then made to see if the user selected the second radio button (Use the address below). If so, the form fields are checked to see if they are empty. If they are, the page is reloaded with the error GET variable so that the error message can be displayed.

If the form is not empty, add the address to the delivery_addresses table and update the orders table:


$addsql = "INSERT INTO

delivery_addresses(forename, surname, add1, add2, add3, postcode, phone, email) VALUES('". strip_tags(addslashes($_POST['forenameBox'])) . "', '". strip_tags(addslashes($_POST['surnameBox'])) . "', '". strip_tags(addslashes($_POST['add1Box'])) . "', '". strip_tags(addslashes($_POST['add2Box'])) . "', '"

. strip_tags(addslashes($_POST['add3Box'])) . "', '". strip_tags(addslashes($_POST['postcodeBox'])) . "', '". strip_tags(addslashes($_POST['phoneBox'])) . "', '"

. strip_tags(addslashes($_POST['emailBox'])) . "')";

mysql_query($addsql);

$setaddsql = "UPDATE orders SET delivery_add_id = " . mysql_insert_id() . ",status = 1 WHERE id = ". $_SESSION['SESS_ORDERNUM'];

mysql_query($setaddsql);

header("Location: ". $config_basedir . "checkout-pay.php");

}

The delivery_addresses table contains a list of addresses for unregistered users and registered users who select a different address. When the information is added to the table, the strip_tags() function removes any HTML tags that may have been added, and the addslashes() function escapes any quotes.

Finally, the orders table is updated with the id of the record from delivery_addresses, and the status is changed to 1. When this is complete, the page redirects to checkout-pay.php.

If the user is logged in but selects the address on file, the orders table is updated also:


else

{

$custsql = "UPDATE orders SET delivery_add_id = 0, status = 1 WHERE id = " . $_SESSION['SESS_ORDERNUM'];

mysql_query($custsql);

header("Location: " . $config_basedir. "checkout-pay.php");

}

}

If no user is logged in, the form is validated and the address is added to the database:


else

{

if(empty($_POST['forenameBox']) ||

empty($_POST['surnameBox']) ||

empty($_POST['add1Box']) ||

empty($_POST['add2Box']) ||

empty($_POST['add3Box']) ||

empty($_POST['postcodeBox']) ||

empty($_POST['phoneBox']) ||

empty($_POST['emailBox']))

{

header("Location: " . "checkout-address.php?error=1");

exit;

}

$addsql = "INSERT INTO

delivery_addresses(forename, surname, add1,

add2, add3, postcode, phone, email)

VALUES('"

. $_POST['forenameBox'] . "', '"

. $_POST['surnameBox'] . "', '"

. $_POST['add1Box'] . "', '"

. $_POST['add2Box'] . "', '"

. $_POST['add3Box'] . "', '"

. $_POST['postcodeBox'] . "', '"

. $_POST['phoneBox'] . "', '"

. $_POST['emailBox'] . "')";

mysql_query($addsql);

$setaddsql = "UPDATE orders

SET delivery_add_id = " . mysql_insert_id()

. ", status = 1 WHERE session = '"

. session_id() . "'";

mysql_query($setaddsql);

header("Location: " . $config_basedir . "checkout-pay.php");

}

}

In this Tutorial of code, the address is added to the delivery_addresses table, and the orders table is updated with the delivery_addresses id and the status is set to 1.

Paying

The final part of the checkout process is to take payment. Dealing with payments on a Web site can take a variety of different routes: PayPal, NOCHEX, Worldpay, and more. This project offers two payment methods: PayPal and checks. These two methods demonstrate how to deal with automatic (PayPal) and manual (check) purchases.

Create a new file called checkout-pay.php and write the following code:


<?php

session_start();

require("config.php");

require("functions.php");

if($_POST['paypalsubmit'])

{

$upsql = "UPDATE orders SET status = 2, payment_type = 1 WHERE id = " . $_SESSION['SESS_ORDERNUM'];

$upres = mysql_query($upsql);

$itemssql = "SELECT total FROM orders WHERE id = " . $_SESSION['SESS_ORDERNUM'];

$itemsres = mysql_query($itemssql);

$row = mysql_fetch_assoc($itemsres);

if($_SESSION['SESS_LOGGEDIN'])

{

unset($_SESSION['SESS_ORDERNUM']);

}

else

{

session_register("SESS_CHANGEID");

$_SESSION['SESS_CHANGEID'] = 1;

}

header("Location: https://www.paypal.com/ cgi-bin/webscr?cmd=_xclick&business=you%40youraddress.com&item_name=". urlencode($config_sitename)

. "+Order&item_number=PROD" . $row['id']."&amount=" . urlencode(sprintf('%.2f',$row['total'])) . "&no_note=1&currency_code=GBP&lc=GB&submit.x=41&submit.y=15");

}

else if($_POST['chequesubmit'])

{

$upsql = "UPDATE orders SET status = 2,payment_type = 2 WHERE id = ". $_SESSION['SESS_ORDERNUM'];

$upres = mysql_query($upsql);

if($_SESSION['SESS_LOGGEDIN'])

{

unset($_SESSION['SESS_ORDERNUM']);

}

else

{

session_register("SESS_CHANGEID");

$_SESSION['SESS_CHANGEID'] = 1;

}

require("header.php");

?>

<h1>Paying by cheque</h1>

Please make your cheque payable to

<strong><?php echo $config_sitename; ?></strong>.

<p>

Send the cheque to:

<p>

<?php echo $config_sitename; ?><br>

22, This Place,<br>

This town,<br>

This county,<br>

FG43 F3D.<br>

<?php

}

else

{

require("header.php");

echo "<h1>Payment</h1>";

showcart();

?>

<h2>Select a payment method</h2>

<form action='checkout-pay.php' method='POST'>

<table cellspacing=10>

<tr>

<td><h3>PayPal</h3></td>

<td>

This site uses PayPal to accept

Switch/Visa/Mastercard cards. No PayPal account

is required - you simply fill in your credit

card details

and the correct payment will be taken from your account.

</td>

<td><input type="submit" name="paypalsubmit" value="Pay with PayPal"></td>

</tr>

<tr>

<td><h3>Cheque</h3></td>

<td>

If you would like to pay by cheque, you can post the cheque for the final amount to the office.

</td>

<td><input type="submit" name="chequesubmit" value="Pay by cheque"></td>

</tr>

</table>

</form>

<?php

}

require("footer.php");

?>

Now we discuss above code step by step:


<h2>Select a payment method</h2>

<form action='checkout-pay.php' method='POST'>

<table cellspacing=10>

<tr>

<td><h3>PayPal</h3></td>

<td>

This site uses PayPal to accept

Switch/Visa/Mastercard cards. No PayPal account

is required – you simply fill in your credit

card details

and the correct payment will be taken from your account.


</td>

<td><input type="submit" name="paypalsubmit" value="Pay with PayPal"></td>

</tr>

<tr>

<td><h3>Cheque</h3></td>

<td>

If you would like to pay by cheque, you can post the cheque for the final amount to the office.


</td>

<td><input type="submit" name="chequesubmit" value="Pay by cheque"></td>

</tr>

</table>

</form>

This simple form provides two Submit buttons only—one to pay by PayPal and the other to pay by check. Processing the form involves two main sections—one for PayPal and one for the check.

At the top of the file, begin adding the code:


<?php

session_start();

require("config.php");

require("functions.php");

If the user clicks the PayPal button, process the order:

if($_POST['paypalsubmit'])

{

$upsql = "UPDATE orders SET status = 2, payment

_type = 1 WHERE id = " . $_SESSION['SESS_ORDERNUM'];

$upres = mysql_query($upsql);

$itemssql = "SELECT total FROM orders WHERE id = " . $_SESSION['SESS_ORDERNUM'];

$itemsres = mysql_query($itemssql);

$row = mysql_fetch_assoc($itemsres);

The orders table is updated to reflect the completion of the order. The status field is changed to 2 and the payment_type field is set to 1 (PayPal). A query then gets the total price from the order so that the PayPal link can be constructed later.

Reset the order session:


if($_SESSION['SESS_LOGGEDIN'])

{

unset($_SESSION['SESS_ORDERNUM']);

}

else

{

session_register("SESS_CHANGEID");

$_SESSION['SESS_CHANGEID'] = 1;

}

If the user is logged in, the SESS_ORDERNUM session variable is removed with unset(). If not, a new session variable called SESS_CHANGEID is created. The next time header.php is loaded, the code at the top of header.php will regenerate the new session and id.

Redirect to www.paypal.com with the payment details:

."&amount=" . urlencode(sprintf('%.2f',$row['total'])) . "&no_note=1&currency_code=GBP&lc=GB&submit.x=41&submit.y=15");

}

On this line, a series of GET variables pass data to the PayPal Web site. These GET variables are reserved words that PayPal can use to process the order.

Table 6-4 explains the purpose of each variable.

It is important to remember that any textual information transmitted as a GET variable should be run through urlencode() to escape nonstandard characters. Start writing the code to process a check payment.

The code is similar to the PayPal code.


else if($_POST['chequesubmit'])

{

$upsql = "UPDATE orders SET status = 2,payment_type = 2 WHERE id = ". $_SESSION['SESS_ORDERNUM'];

$upres = mysql_query($upsql);

Here you again update the orders table, but this time the payment_type is 2 instead of 1.

Reset the order as you did previously:

$upres = mysql_query($upsql);

if($_SESSION['SESS_LOGGEDIN'])

{

unset($_SESSION['SESS_ORDERNUM']);

}

else

{

session_register("SESS_CHANGEID");

$_SESSION['SESS_CHANGEID'] = 1;

}

Finally, display the details of where the user should send the check:

require("header.php");

?>

<h1>Paying by cheque</h1>

Please make your cheque payable to

<strong><?php echo $config_sitename; ?></strong>.

<p>

Send the cheque to:

<p>

<?php echo $config_sitename; ?><br>

22, This Place,<br>

This town,<br>

This county,<br>

FG43 F3D.<br>

<?php

}

The processing is now complete

Open the block to display the form. Before you reach the form, however, add the showcart() function to summarize the current cart:


else

{

require("header.php");

echo "<h1>Payment</h1>";

showcart();

?>

<h2>Select a payment method</h2>

<form action='checkout-pay.php' method='POST'>

Finally, add the closing code:


<?php

}

require("footer.php");

?>

Your brand-new, home-grown payment screen should now resemble Figure 6-8.

Shopping Payment Gateway using php

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor’s degree in Engineering from State University Of Bangladesh, I’m also a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, CIDA and MAX Group where I worked on ERP software and web development., but now i’m a co-founder and Chief Executive Officer and Managing Director of TechBeeo Software Consultancy Services Ltd. I’m also a Course Instructor of ZCE PHP 5.3 Certification and professional web development course at IBCS-PRIMAX Software (Bangladesh) Limited – a leading Training Institute in the country.
Print Friendly
10 comments on “Build a shopping cart with php part-2
  1. This was an excellent learning tool and by far the best example PHP shopping cart tutorial. Your line by line example explanations really sets this example heads and shoulders above the typical useful but primitive examples Bravo!

  2. Hey pls help me get rid of this error in header.php line 27
    i made the modifications as per said.but even then i get this

    Parse error: parse error in C:\wamp\www\go4shop\header.php on line 27

    • In header.php line 2 instead of double quote use the single quote in echo syntax. for ex. :-
      echo ‘Logged in as ‘ . $_SESSION[‘SESS_USERNAME’]. ‘[logout]’;

      Thanks.

  3. first of all sincerely thank the author.
    I have a problem that can not understand why when I do not login:

    Notice: Undefined index: SESS_LOGGEDIN in D:\xampp\htdocs\shopcart\checkout-pay.php on line 14

    Fatal error: Call to undefined function session_register() in D:\xampp\htdocs\shopcart\checkout-pay.php on line 20

Leave a Reply

Your email address will not be published. Required fields are marked *

*