jump to navigation

Storing Objects to Sessions in PHP July 15, 2007

Posted by ordinarywebguy in PHP.
trackback

Its been a quite some time since doing something different other than having a CRUD Application projects. And this is all about to a simple shopping cart application. Yeah! So yummy having me to learn something new which I crave for most. I have this book of Larry Ullman titled “PHP Advance: For the World Wide Web”. It includes a section regarding ecommerce especifically shopping cart. Simple shopping cart without payment integration. It helped me a lot into completion of this project.

Take a look to its code:

ShoppingCart.class.php

<?php
class ShoppingCart {

# public vars
var $mItems;

# private vars
var $mPrice;
var $mName;

function ShoppingCart() {
$this->mItems = array();
$this->mPrice = array();
$this->mName = array();
} # end function

function AddItem($item) {
if ($this->mItems[$item]) {
$this->mItems[$item] += 1;
} else {
$this->mItems[$item] = 1;
} # end if
} # end function

function DropItem($item) {
$this->mItems[$item] = 0;
} # end function

function ChangeQuantity($item, $quantity) {
if ($quantity == 0) {
$this->DropItem($item);
} else {
$this->mItems[$item] = $quantity;
} # end if
} # end function

function DisplayCart() {
global $config, $_SESSION;

if (count($this->mItems) > 0) {
$prod = & new Data(’scart_product’);
$fields = $prod->GetFields();

$ret =

<script type=”text/javascript” src=”js/common.js”></script>
<script type=”text/javascript”>
function check_min_total() {
if (document.cart_frm.total.value < ‘ . $config['MIN_PRICE_ORDER'] . ‘) {
alert(“Cannot Proceed Checkout! \n Minimum Price Order: ‘ . $config['CURRENCY_SYMBOL'] . $config['MIN_PRICE_ORDER'] . ‘”);
return false;
} else {
//return true;
document.location = “checkout.php”;
} // end if
} // end function
</script>

<form name=”cart_frm” action=”cart.php?do=change” method=”post”>
<table>
<tr>
<td align=”center”><strong>Product Name</strong></td>
<td align=”center”><strong>Price Per Unit</strong></td>
<td align=”center”><strong>Quantity</strong></td>
<td align=”center”><strong>Total</strong></td>
<td align=”center”><strong>Delete</strong></td>
</tr>
‘;

foreach ($this->mItems as $k => $v) {
if ($v != 0) {

$data = $prod->GetOneData($fields, “WHERE product_id = $k”);
$sub_total = sprintf(“%01.2f”, ($v * $data['product_price']));
$total += $sub_total;

$this->mPrice[] = $data['product_price'];
$this->mName[] = $data['product_name'];

$ret .= “
<tr>
<td align=\”center\”>{$data['product_name']}</td>
<td align=\”center\”>{$config['CURRENCY_SYMBOL']}{$data['product_price']}</td>
<td align=\”center\”><input type=\”text\” name=\”id[$k]\” value=\”{$v}\” size=\”2\” maxsize=\”3\” /></td>
<td align=\”center\”>{$config['CURRENCY_SYMBOL']}{$sub_total}</td>
<td align=\”center\”><a href=\”cart.php?id=$k&do=drop\” onclick=\”return confirmation(‘Are you sure you want to delete product: {$data['product_name']}?’);\”><img src=\”images/button_delete.gif\” border=\”0\” title=\”delete\” /></a></td>
</tr>\n
“;
} # end if
} # end foreach

$ret .= ‘
<tr>
<td colspan=”5″> </td>
</tr>
<tr>
<td align=”right” colspan=”3″><strong>Total</strong></td>
<td align=”center”><strong>’ . $config['CURRENCY_SYMBOL'] . sprintf(“%01.2f”, $total). ‘</strong></td>
<td align=”center”> </td>
</tr>
<input type=”hidden” name=”total” value=”‘ . $total . ‘” />
<input type=”hidden” name=”do” value=”change” />
</table>

<br />
<!–Alter the quantities by changing the above values and clicking here –>
<center><input type=”submit” name=”submit” value=”Change Quantities” /> <input type=”button” value=”Back to shopping” onclick=”document.location=\’retail_food_products.php\’” /> <input type=”button” value=”Proceed to checkout” onclick=”return check_min_total();” style=”font-weight: bold;” /></center>
</form>
<noscript><div align=”center” style=”font-weight: bold; color: #FF0000;”>In order to proceed checkout: Please turn on javascript in your browser. </div></noscript>
‘;

$_SESSION['min_price_order'] = $total;

} else {
$ret .= ‘<br /><font color=”#CC0000″><big>Your shopping cart is currently empty.</big></font>’;
} # end if

return $ret;
} # end function
} # end class
?>

Take note: I’ve already modified it.
cart.php

<?php
require “config.php”;
require $config['LIBS_DIR'] . “MySqlDb.class.php”;
require $config['LIBS_DIR'] . “Data.class.php”;
require $config['INC_DIR'] . “db_open.php”;
require $config['DOC_ROOT'] . “config_settings.php”;
require $config['LIBS_DIR'] . “ShoppingCart.class.php”;
require $config['LIBS_DIR'] . “functions.php”;

if (isset($_SESSION['cart'])) {
$cart = unserialize($_SESSION['cart']);
} else {
$cart = & new ShoppingCart();
} # end if

$do = trim($_GET['do']);
$id = (int) trim($_GET['id']);

switch ($do) {
case ‘add’:
$cart->AddItem($id);
print $cart->DisplayCart();
header(“Location: {$_SERVER['PHP_SELF']}”);
break;

case ‘drop’:
$cart->DropItem($id);
unset($cart->mItems[$id]);
print $cart->DisplayCart();
header(“Location: {$_SERVER['PHP_SELF']}”);
break;

case ‘change’:
if ($_SERVER['REQUEST_METHOD'] == “POST”) {
foreach ($_POST['id'] as $k => $v) {
if ($v == 0) {
$cart->DropItem($k);
unset($cart->mItems[$k]);
} else {
$cart->ChangeQuantity($k, $v);
} # end if
} # end foreach
print $cart->DisplayCart();
} # end if
header(“Location: {$_SERVER['PHP_SELF']}”);
break;

case ‘display’:
default:
print $cart->DisplayCart();
break;
} # end switch

$_SESSION['cart'] = serialize($cart);
?>

Notice on cart.php file on this line:

$_SESSION['cart'] = serialize($cart);

Its the way of storing objects to sessions. :) And when retrieving it:

if (isset($_SESSION['cart'])) {
$cart = unserialize($_SESSION['cart']);
} else {
$cart = & new ShoppingCart();
} # end if

That’s it. Now I have my simple shopping cart application.

Comments»

1. Json - January 23, 2008

Pretty ironic. I am working on a shopping cart and was having trouble figuring out how to store objects into an array when I found this article! Good read but wasn’t quite was I was looking for though.

2. name - September 1, 2008

Good day!,

3. name - September 1, 2008

Hi!,

4. sai narasimha reddy - October 4, 2008

thanx bro good tut!

5. John Pyle - December 3, 2008

Elegant :-)

6. Matt Kendrick - August 17, 2009

Used this trick a number of times. Real easy to do.