13
May 10

Shopping Cart in PHP

Here is part of my shopping cart project which I created during my PHP / MySQL studies. Needless to say it is good only for studying purposes because it is insecure and quite immature:

The funniest thing is that one of the requirements for this cart was to be in just 2 files. So because I couldn't imagine to fit it in two files I just fitted it in 2 :) Let the fun begin:

go back to the store and begin shopping :).';
 
// If post input with 'do' values is coming from the admin area forms we will process it here. This is because we have to use get otherwise the URL will become too long especially when we specify long description for products.
 
switch ($_POST['do']) { 
 
	case 'insert':
		$command = "insert into shop_products (prouct_name, price, product_image, description) values('".addslashes($_POST['product_name'])."','".addslashes($_POST['price'])."','".addslashes($_POST['product_image'])."','".addslashes($_POST['description'])."');";
		$result = mysql_query($command);
		print "Data was successfully entered.
";
		mysql_close($db);
		exit();
		break;
 
	case 'update':
		$command = "update shop_products set prouct_name='".addslashes($_POST['product_name'])."', price='".addslashes($_POST['price'])."', product_image='".addslashes($_POST['product_image'])."', description='".addslashes($_POST['description'])."' where product_id='".$_POST['product']."';";
		$result = mysql_query($command);
		print "Data was successfully updated.
";
		mysql_close($db);
		exit();
		break;
}
 
//Since we are limited to the number of pages we will use switch to simulate all the pages we want :)
<span id="more-223"></span>
switch ($_GET['page']) {
 
/* #################################################
 * #                  Checkout                     #
 * ################################################# */
 
//Our checkout page
    case 'checkout':
        if (!$_SESSION['logged']) {
 
	echo 'Attention: You have to be registered and logged in in order to check out.
 
';
	echo "Please <a href="index.php?page=registration_form"> register </a> or <a href="index.php?page=login">log in</a> first.";
	exit();
}
 
if ($_SESSION['cart']) {
 
//this is the total price
$total = 0;
 
function subtotal($price,$quantity) {
	$subtotal = ($price*$quantity) + ($price*$quantity*$tax); //multiplied by quantity and tax
	return $subtotal;
	}
 
echo "Your cart contains:";
 
$purchase = '';
 
while (list($key, $value) = each($_SESSION['cart'])) {
 
	//Get the price of each product
	$products_query = mysql_query("select product_id,price from shop_products where prouct_name = '$key';");
	$products = mysql_fetch_object($products_query);
 
    echo "
 $value pounds $key at the price $".$products-&gt;price.".";
    $subtotal = subtotal($products-&gt;price,$value);
    echo " Subtotal: $ $subtotal";
    $total += $subtotal;
 
    //Here we will insert it into the database
    $command = "insert into shop_purchases (date, user_id, product_id, quantity) values(curdate(),".$_SESSION['user_id'].",$products-&gt;product_id,'$value');";
	$result = mysql_query($command);
 
    //We will also add a description for the paypal purchase
    $purchase .= $key.' x '.$value;
    $purchase .= ' &amp; ';
 
}
 
$tax=0.08;
$total += $total*$tax;
echo '
 
Total with TAX: $'.$total;
echo '
Purchase recorded in the database. Please proceed with the payment';
 
//We will just add the email for the customer in case he pays with different paypal account
//All the time we have used the email as indicator for the user being logged in
//After that we can look up the address for that email from shadow.php
$purchase .= 'customer = '.$_SESSION['logged'];
 
//At this time only PayPal checkout is available
echo "
 
Check out with Paypal:";
 
echo &lt;&lt;
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input name="cmd" type="hidden" value="_xclick" />
<input name="business" type="hidden" value="pi4a@pi4a.com" />
<input name="item_name" type="hidden" value="$purchase" />
<input name="item_number" type="hidden" />
<input name="amount" type="hidden" value="$total" />
<input name="no_note" type="hidden" value="1" />
<input name="currency_code" type="hidden" value="USD" />
<input name="bn" type="hidden" value="PP-BuyNowBF" />
<input alt="Make payments with PayPal - it's fast, free and secure!" name="submit" src="https://www.paypal.com/en_US/i/btn/x-click-but23.gif" type="image" />
</form>
 
PAYPAL;
} else {
	echo 'Your cart is empty so there is nothing to check out.';
	echo $begin_shopping;
	}
        break;
 
/* #################################################
 * #                  Logout                       #
 * ################################################# */
 
// A simple log out function
 
    case 'logout':
    echo 'You are now logged out';
    unset($_SESSION['logged']);
    unset($_SESSION['admin']);
        break;
 
/* #################################################
 * #                  View cart                    #
 * ################################################# */
 
// Our cart
 
    case 'cart':
 
//The standard extract to remove $_GET from the Get variables
//I have not used it for all scripts because it will be too obfuscating at times
extract($_GET, EXTR_PREFIX_SAME, "get");
 
//2 functions to cut off code
 
// this function will show what the cart contains
function cart_contains() {
	echo "Your cart contains now:
";
	while (list($key, $value) = each($_SESSION['cart'])) {
	echo $key.' '.$value.' pound(s)
';
	}
}
 
function add_to_cart($product,$pounds){
 $_SESSION['cart'][$product] += $pounds;
 echo "You have added $pounds pounds $product to your cart.
";
 return $_SESSION['cart'];
}
 
//we define 4 cases depending on the availability of sessions and product variables
 
if (!($_SESSION['cart']) &amp;&amp; !($product)) {
	echo 'Your cart is empty.';
	echo $begin_shopping;
	exit;
} elseif (!($_SESSION['cart']) &amp;&amp; ($product)) {
	$_SESSION['cart']= array();
	add_to_cart($product,$pounds);
	cart_contains();
} elseif (($_SESSION['cart']) &amp;&amp; !($product)) {
	cart_contains();
} else {
	add_to_cart($product,$pounds);
	cart_contains();
}
        break;
 
/* #################################################
 * #                  Login                        #
 * ################################################# */
 
// A login page
 
		case 'login':
 
if ($_SESSION['logged']) {
	echo 'You are logged in with email: '.$_SESSION['logged'];
	exit();
	} elseif (!$_SESSION['logged']) {
 
if (!$_GET['email']) {
 
//We will have to use GET even for the login page in order to set page=login with a hidden value later
//I know it is very insecure and POST should be used instead
 
echo &lt;&lt;
<form>
<input name="page" type="hidden" value="login" />
<table>
<tbody>
<tr>
<td align="left">
Email: <input name="email" size="25" type="text" /></td>
</tr>
<tr>
<td align="left">
Pass: <input name="password" size="25" type="password" /></td>
</tr>
<tr>
<td align="left">
<input type="submit" value="SUBMIT" /></td>
</tr>
</tbody>
</table>
FORM;
exit();
}
 
extract($_GET, EXTR_PREFIX_SAME, "get");
 
$users = mysql_query("select user_id, email, password from shop_users where email = '$email'"); 
 
while ($data = mysql_fetch_object($users)) {
 
//First I make sure there is a $_GET['email']. Otherwise there is a bug which validates emtpy logins.
//Then I compare for equality the two strings for email and password
 
if ($email &amp;&amp; $email == $data-&gt;email &amp;&amp; $password == $data-&gt;password) {
	echo "You have successfully logged in.";
		$_SESSION['logged']= $email;
		$_SESSION['user_id'] = $data-&gt;user_id;
 
//A check to see if the logged in user is admin
//The admin is the user with user_id = 1. This makes sense because the first user to register should be the admin.
if ($data-&gt;user_id == 1) {
	$_SESSION['admin'] = 1;
 	echo "You are an admin user. Please refresh to see the admin menu";
}
exit();
}                
 
}
} 
 
//If it reaches this point die with an error
die('Incorrect login!');
        break;
 
/* #################################################
 * #                Registration                   #
 * ################################################# */
 
// Registration form 
 
        case 'registration_form':
?&gt;
<table>
<tbody>
<tr>
<td colspan="2" align="left"></td>
</tr>
<tr>
<td align="right">
Name:</td>
<td>
<input name="name" size="25" type="text" value="&lt;? echo $_GET['name']; ?&gt;" /></td>
</tr>
<tr>
<td align="right">
Email:</td>
<td align="left">
<input name="email" size="25" type="text" value="&lt;? echo $_GET['email']; ?&gt;" /></td>
</tr>
<tr>
<td align="right">
Address:</td>
<td align="left">
<input name="address" size="25" type="text" value="&lt;? echo $_GET['address']; ?&gt;" /></td>
</tr>
<tr>
<td colspan="2" align="left">
How did you hear about us?
<ul>
<input name="found" type="radio" value="wordofmouth" />Word of Mouth
 
<input name="found" type="radio" value="search" />Online Search
 
<input name="found" type="radio" value="article" />Printed publication/article
 
<input name="found" type="radio" value="other" />Other</ul>
</td>
</tr>
<tr>
<td colspan="2">
<input checked="checked" name="spam" type="checkbox" />Please email me all kinds of stuff.</td>
</tr>
<tr>
<td colspan="2">
<input name="tos" type="checkbox" />I have read and accept Terms of service.</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="SUBMIT" /></td>
</tr>
</tbody>
</table>
</form>
<table>
<tbody>
<tr>
<td>Product name:</td>
<td> <input name="product_name" type="text" /></td>
</tr>
<tr>
<td>Price:</td>
<td><input name="price" type="text" /></td>
</tr>
<tr>
<td>Image URL:</td>
<td> <input name="product_image" type="text" /></td>
</tr>
<tr>
<td>Description:</td>
<td> <textarea cols="40" rows="6" name="description"></textarea></td>
</tr>
</tbody>
</table>
<input name="do" type="hidden" value="insert" />
<input name="submit" type="submit" value="submit" />
 
ADD_PRODUCT_FORM;
exit();
 
} elseif ($_GET['action'] == 'delete' &amp;&amp; $_GET['product'] ) {
 
$product_id = $_GET['product'];
 
mysql_query("delete from shop_products where product_id = '$product_id' limit 1");
 
exit ("Selected product deleted from cart");
} elseif ($_GET['action'] == 'modify' &amp;&amp; $_GET['product'] ) {
 
//Here is the page for the modification of product
$query="select prouct_name, price, product_image, description from shop_products where product_id='".$_GET['product']."';";
$modify = mysql_query($query);
$modification = mysql_fetch_object($modify);
 
$product=$_GET['product'];
 
echo &lt;&lt;<form action="index.php" method="post">
<table>
<tbody>
<tr>
<td>Product name:</td>
<td> <input name="product_name" type="text" value="$modification-&gt;prouct_name" /></td>
</tr>
<tr>
<td>Price:</td>
<td><input name="price" type="text" value="$modification-&gt;price" /></td>
</tr>
<tr>
<td>Image URL:</td>
<td> <input name="product_image" type="text" value="$modification-&gt;product_image" /></td>
</tr>
<tr>
<td>Description:</td>
<td> <textarea cols="40" rows="6" name="description">$modification-&gt;description</textarea></td>
</tr>
</tbody>
</table>
<input name="do" type="hidden" value="update" />
<input name="product" type="hidden" value="$product" />
<input name="submit" type="submit" value="submit" />
</form>
 
MODIFY_PRODUCT_FORM;
exit();
}
//This is the default sub-case when we get all the products listed
 
echo "
";
echo "
 
";
 
$result = mysql_query('select * from shop_products');
while ($data = mysql_fetch_object($result)) {
    print "
 
\n";
}
echo "
<table border="1">
<tbody>
<tr>
<th>product name</th>
<th>price</th>
<th>image_url</th>
<th>description</th>
<th>modify</th>
<th>delete</th>
</tr>
<tr>
<td>".$data-&gt;prouct_name."</td>
<td>".$data-&gt;price."</td>
<td>". $data-&gt;product_image."</td>
<td>".$data-&gt;description."</td>
<td> <a href="index.php?page=admin&amp;action=modify&amp;product=">product_id."&gt;V</a></td>
<td> <a href="index.php?page=admin&amp;action=delete&amp;product=">product_id."&gt;X</a></td>
</tr>
</tbody>
</table>
";
echo "<a href="index.php?page=admin&amp;action=add_product">Add a new product</a>";
} else {
	die('Sorry. No access');
}
 
        break;
 
/* #################################################
 * #   Admin Page - View customers                 #
 * ################################################# */    
 
        case 'view_customers':
 
//a check to make sure this is admin
if ($_SESSION['admin']){
echo "Customers
";
echo "
";
echo "
 
";
 
$result = mysql_query('select * from shop_users');
while ($data = mysql_fetch_object($result)) {
    print "
 
\n";
}
echo "
<table border="1">
<tbody>
<tr>
<th>email</th>
<th>name</th>
<th>password</th>
<th>reference</th>
<th>address</th>
</tr>
<tr>
<td>".$data-&gt;email."</td>
<td>".$data-&gt;name."</td>
<td>".$data-&gt;password."</td>
<td>".$data-&gt;reference."</td>
<td>".$data-&gt;address."</td>
</tr>
</tbody>
</table>
";
} else {
	die('Sorry. No access');
}
        break;
 
/* #################################################
 * #   Admin Page - View purchases                 #
 * ################################################# */    
 
        case 'view_purchases':
//a check to make sure this is admin
if ($_SESSION['admin']){
echo "Purchases
";
echo "
";
echo "
 
";
 
$result = mysql_query("select sp.date, group_concat(concat(spr.prouct_name,' ', sp.quantity, ' pounds') separator ', ') as purchases, su.name from (shop_purchases as sp left join shop_users as su on sp.user_id = su.user_id) left join shop_products as spr on sp.product_id=spr.product_id group by name;");
while ($data = mysql_fetch_object($result)) {
    print "
 
\n";
}
echo "
<table border="1">
<tbody>
<tr>
<th>date</th>
<th>purchases</th>
<th>name</th>
</tr>
<tr>
<td>".$data-&gt;date."</td>
<td>".$data-&gt;purchases."</td>
<td>".$data-&gt;name."</td>
</tr>
</tbody>
</table>
";
} else {
	die('Sorry. No access');
}
        break;       
 
/* #################################################
 * #                  Default Index                #
 * ################################################# */
 
//The default index
 
        default:
 
echo '
<h2>Our hot offers include:</h2>
';
 
echo '
';
 
$products = mysql_query("select * from shop_products");
while ($data = mysql_fetch_object($products)) {
 
    echo '
 
';
    echo '
 
FORM;
}
 
echo '
<table>
<tbody>
<tr>
<td><img src="'.$data-&gt;product_image.'" alt="" />'.'</td>
<td>'."$data-&gt;prouct_name - ".$data-&gt;description;
    echo "
 
"."Price: $".$data-&gt;price.' per pound';
 
//In the form I will add a hidden value page = cart so that it goes to the cart case
 
echo &lt;&lt;
<form>
Pounds: <input maxlength="3" name="pounds" size="2" type="text" value="1" />
<input name="product" type="hidden" value="$data-&gt;prouct_name" />
<input name="page" type="hidden" value="cart" />
<input type="submit" value="Get" />
</form></td>
</tr>
</tbody>
</table>
';
        break;
}
mysql_close($db);
?&gt;