Jump to content

[SOLVED] help me develope a simple shopping cart class with sessions


saeed_violinist

Recommended Posts

Dear Friends,

 

Its my firsw walk in OOP, I want to make a simple shopping cart and I dont know how to make variables with sessions, I end up with this peace of code :

 

class CLS_CART {

var $items; // ITEMs


function CRT_AddItem($code, $id, $fname, $price, $qty = 1) {
	$this->items[$code]["id"]          = $id;
	$this->items[$code]["fname"]    = $fname;
	$this->items[$code]["price"]      = $price;
	$this->items[$code]["qty"]	      = $qty;
}

function CRT_UpdateItem() {
// update functions goes here	
}

function CRT_ShowCart($item) {

	foreach ($items as $key => $val) {
		echo $key . " ----> " . $val;
	}
}

}

 

I just need to know how can I make it from sessions, a few tips and tricks will put me in line to the end!

 

thanks in advance.

 

 

Link to comment
Share on other sites

This might sound like a bit off topic, but instead of sessions(well all sessions) try this a mysql table with cart data and a session with their cart data so that you are transferring less data in sessions (saves stress on server/user load) just when they add that first item it creates a new cartID in the table and a row for each item in the cart, them you make a second cron job that purges the table seeking out entries older than say 10 days. 

Link to comment
Share on other sites

This might sound like a bit off topic, but instead of sessions(well all sessions) try this a mysql table with cart data and a session with their cart data so that you are transferring less data in sessions (saves stress on server/user load) just when they add that first item it creates a new cartID in the table and a row for each item in the cart, them you make a second cron job that purges the table seeking out entries older than say 10 days. 

 

Thanks, sounds good but I still dont know how I can expand my class because It will do the job, and most important thing is with help of you guys, I can learn something about OOP.

 

and can you tell more about your idea? how can I create a row for uniqe visitors and uniqe shopping carts?

Link to comment
Share on other sites

my_page.php

<?php
include('cart.php'); // note the class definition has to be before session_start
session_start();
if (!isset($_SESSION['cart']) || $_GET['reset'] == 1) {
    $_SESSION['cart'] = new CLS_CART();
}
$cart = $_SESSION['cart']; // unsure if you add the reference &= here if the endpage part is unnecessary.

// do processing here


// to end the page do this:
$_SESSION['cart'] = $cart;
?>

 

 

Note the spaces are a result of not using the code tags.

cart.php

<?php
class CLS_CART {






var $items; // ITEMs




function CRT_AddItem($code, $id, $fname, $price, $qty = 1) {





$this->items[$code]["id"]          = $id;





$this->items[$code]["fname"]    = $fname;





$this->items[$code]["price"]      = $price;





$this->items[$code]["qty"]



      = $qty;



}






function CRT_UpdateItem() {



// update functions goes here






}






function CRT_ShowCart($item) {





foreach ($items as $key => $val) {







echo $key . " ----> " . $val;





}



}




}
?>

Link to comment
Share on other sites

I didnt noticed any changes to my orginal class posted on top. you mean it was OK!? lucky me because it is my first time to write a class  ;D and if not can you please fix it to be work fine? atleast optimizing the "CRT_AddItem" function will push me forward greatly.

 

and for "my_page.php" you created, can this whole process be done without any query string in url? I mean by POST method?

 

and last thing, I need an example for filling shopping cart with 2 items (just the pure php code).

 

Thanks a lot.

 

 

 

Link to comment
Share on other sites

Anyway I managed to write my first class and as you will see its fully ( I hope ) functional!

 

As I said before, My problem is I dont know how to pass variables from a sessions to this class so each user have a unique cart. PLEASE SOME ONE GUIDE ME!

 

MY CLASS ->

<?php
# Start Shopping Cart Class

class CLS_CART {
# Member Variables
var $items;	// items in cart
var $total; // total cart price

# Cart Class Constructor
function CLS_CART() {
	$this->items = array(); // inititalize empty an array
	$this->total = 0;		// inititalize total price to zero
}

# Add Items To Cart
function CRT_AddItem($id, $name, $price, $qty = 1) {		
	// check to verify item is in cart or not
	if(!isset($this->items[$id])) {
		// add to cart
		$this->items[$id][name]  = $name;
		$this->items[$id][price] = $price;
		$this->items[$id][qty]	 = $qty; 
	}		
}

# Update Items In Cart
function CRT_UpdateItemQTY ($id, $new_qty = 1) {
		// check to verify item is in cart or not
		if(!isset($this->items[$id])) {
			// update item quantity in cart
			$this->items[$id][qty]	 = $qty; 
	}
}

# Remove Item From Cart
function CRT_DelItem($id) {
	if(!isset($this->items[$id])) {
		unset($this->items[$id]); 
	}
}

# Calculate Total Cart Price
function CRT_TotalPrice() {
	$this->total = 0 ; // set total to zero in begining of calculations

	// check if cart is have any items
	if(isset($this->items)) {
		foreach ($this->items AS $key => $val) {
			$this->total += ($this->items[$key][price] * $this->items[$key][qty]);
		}
	}
	return $this->total;
}

# Show Cart
function CRT_ShowCart() {
	$ret = "";
	if(isset($this->items)) {
		$count_items = count($this->items); // count number of items exist in cart
		if (!$count_items == 0) {
			$row_no = 1; // row number starts from 1				
			$ret .= "<table cellpadding=\"1\" cellspacing=\"2\" width=\"100%\" border=\"0\">
						<tr>
							<td width=\"5%\" bgcolor=\"#EFEFEF\" align=\"center\" style=\"font-weight: 600\">row</td>
							<td width=\"50%\" bgcolor=\"#EFEFEF\" align=\"center\" style=\"font-weight: 600\">NAME</td>
							<td width=\"5%\" bgcolor=\"#EFEFEF\" align=\"center\" style=\"font-weight: 600\">QTY</td>
							<td width=\"20%\" bgcolor=\"#EFEFEF\" align=\"center\" style=\"font-weight: 600\">Unit PRICE</td>
							<td width=\"20%\" bgcolor=\"#EFEFEF\" align=\"center\" style=\"font-weight: 600\">Total PRICE</td>
						</tr>\n
			";
			foreach ($this->items AS $id => $val) {
					$ret .= "	<tr>\n";					
					$ret .= "		<td style=\"border: 1px solid #EFEFEF;\" align=\"center\">" . $row_no . "</td>\n";
					$ret .= "		<td style=\"border: 1px solid #EFEFEF;\">" . $this->items[$id][name] . "</td>\n";
					$ret .= "		<td style=\"border: 1px solid #EFEFEF;\" align=\"center\">" . $this->items[$id][qty] . "</td>\n";
					$ret .= "		<td style=\"border: 1px solid #EFEFEF;\" align=\"center\">" . $this->items[$id][price] . "</td>\n";
					$ret .= "		<td style=\"border: 1px solid #EFEFEF;\" align=\"center\">" . ($this->items[$id][price] * $this->items[$id][qty]) . "</td>\n";
					$ret .= "	</tr> \n";
					$row_no++; // add 1 to row number				
			}
			$ret .= "</table>";
			$ret .= "<table width=\"100%\"><tr><td align=\"right\" style=\"font-weight: 600;\"TOTAL: <span style=\"font-weight: 600; color=red\">" . $this->CRT_TotalPrice() . "</span></td></tr></table>";
		} else {
			$ret .= "YOUR CART IS EMPTY!";
		}
	}
	return $ret;
}


} // END CLS_CART
?>

 

SAMPLE USAGE ->

<?php
include"cart.php";
$_CART = new CLS_CART();

$_CART->CRT_AddItem (1,'apple', 2, 3);
$_CART->CRT_AddItem (2,'orange', 3, 2);
$_CART->CRT_AddItem (3,'sugar', 1.99, 0.75);

?>
<html>

  <?php print $_CART->CRT_ShowCart(); ?>

</html>

 

[attachment deleted by admin]

Link to comment
Share on other sites

Using session_start is a good start than using $_SESSION inside the class would also be another good start.

 

If you want to store the cart in session see my post above. I gave a plain and simple example of doing just that.

Link to comment
Share on other sites

Ummm....

 

<?php
include('cart.php'); // note the class definition has to be before session_start
session_start();
$_SESSION['test'] = "This is a test<br />";
if (!isset($_SESSION['cart']) || $_GET['reset'] == 1) {
    $_SESSION['cart'] = new CLS_CART();
}
$cart = $_SESSION['cart']; // unsure if you add the reference &= here if the endpage part is unnecessary.

// do processing here


// to end the page do this:
$_SESSION['cart'] = $cart;
?>

 

 

cart.php

<?php
# Start Shopping Cart Class

class CLS_CART {
# Member Variables
var $items;	// items in cart
var $total; // total cart price

# Cart Class Constructor
function CLS_CART() {
	$this->items = array(); // inititalize empty an array
	$this->total = 0;		// inititalize total price to zero
                echo $_SESSION['test'];
}

# Add Items To Cart
function CRT_AddItem($id, $name, $price, $qty = 1) {		
	// check to verify item is in cart or not
	if(!isset($this->items[$id])) {
		// add to cart
		$this->items[$id][name]  = $name;
		$this->items[$id][price] = $price;
		$this->items[$id][qty]	 = $qty; 
	}		
}

# Update Items In Cart
function CRT_UpdateItemQTY ($id, $new_qty = 1) {
		// check to verify item is in cart or not
		if(!isset($this->items[$id])) {
			// update item quantity in cart
			$this->items[$id][qty]	 = $qty; 
	}
}

# Remove Item From Cart
function CRT_DelItem($id) {
	if(!isset($this->items[$id])) {
		unset($this->items[$id]); 
	}
}

# Calculate Total Cart Price
function CRT_TotalPrice() {
	$this->total = 0 ; // set total to zero in begining of calculations

	// check if cart is have any items
	if(isset($this->items)) {
		foreach ($this->items AS $key => $val) {
			$this->total += ($this->items[$key][price] * $this->items[$key][qty]);
		}
	}
	return $this->total;
}

# Show Cart
function CRT_ShowCart() {
	$ret = "";
	if(isset($this->items)) {
		$count_items = count($this->items); // count number of items exist in cart
		if (!$count_items == 0) {
			$row_no = 1; // row number starts from 1				
			$ret .= "<table cellpadding=\"1\" cellspacing=\"2\" width=\"100%\" border=\"0\">
						<tr>
							<td width=\"5%\" bgcolor=\"#EFEFEF\" align=\"center\" style=\"font-weight: 600\">row</td>
							<td width=\"50%\" bgcolor=\"#EFEFEF\" align=\"center\" style=\"font-weight: 600\">NAME</td>
							<td width=\"5%\" bgcolor=\"#EFEFEF\" align=\"center\" style=\"font-weight: 600\">QTY</td>
							<td width=\"20%\" bgcolor=\"#EFEFEF\" align=\"center\" style=\"font-weight: 600\">Unit PRICE</td>
							<td width=\"20%\" bgcolor=\"#EFEFEF\" align=\"center\" style=\"font-weight: 600\">Total PRICE</td>
						</tr>\n
			";
			foreach ($this->items AS $id => $val) {
					$ret .= "	<tr>\n";					
					$ret .= "		<td style=\"border: 1px solid #EFEFEF;\" align=\"center\">" . $row_no . "</td>\n";
					$ret .= "		<td style=\"border: 1px solid #EFEFEF;\">" . $this->items[$id][name] . "</td>\n";
					$ret .= "		<td style=\"border: 1px solid #EFEFEF;\" align=\"center\">" . $this->items[$id][qty] . "</td>\n";
					$ret .= "		<td style=\"border: 1px solid #EFEFEF;\" align=\"center\">" . $this->items[$id][price] . "</td>\n";
					$ret .= "		<td style=\"border: 1px solid #EFEFEF;\" align=\"center\">" . ($this->items[$id][price] * $this->items[$id][qty]) . "</td>\n";
					$ret .= "	</tr> \n";
					$row_no++; // add 1 to row number				
			}
			$ret .= "</table>";
			$ret .= "<table width=\"100%\"><tr><td align=\"right\" style=\"font-weight: 600;\"TOTAL: <span style=\"font-weight: 600; color=red\">" . $this->CRT_TotalPrice() . "</span></td></tr></table>";
		} else {
			$ret .= "YOUR CART IS EMPTY!";
		}
	}
	return $ret;
}


} // END CLS_CART
?>

 

Store your class data in cart.php

 

I already posted this...

 

www.php.net/session

Read up.

Link to comment
Share on other sites

You mean there is no need to use any session in class itself?

 

I have made an index.php to test your suggestion, but the problem is when I call index.php without query string the cart will show empty! please take a moment and see what is going wrong, I think Im very close to make things work!

 

INDEX.PHP for use the CLS_CART class:

<?php
// TEST THIS IN BROWSER TO ADD ITEM TO CART
// http://127.0.0.1/cart/index.php?action=add&id=1&name=apple&price=9.99&no=2

include"cart.php";

session_start();

$_SESSION['cart'] = new CLS_CART();


$action = $_GET["action"];
$id	  	= $_GET["id"];
$no	  	= $_GET["no"];
$name   = $_GET["name"];
$price  = $_GET["price"];

switch ($action) {
// ADD TO CART
case "add" :
$_SESSION['cart']->CRT_AddItem($id, $name, $price, $no);
break;	
// DELETE FROM CART
case "delete" :
	$_SESSION['cart']->CRT_DelItem($id);
	break;
}

?>
<html>

  <?php print $_SESSION['cart']->CRT_ShowCart(); ?>

</html>

Link to comment
Share on other sites

thanks all, I finally made it.

 

include"cart.php";

session_start();

if (!isset($_SESSION['cart']) || $_GET['reset'] == 1) {
    $_SESSION['cart'] = new CLS_CART();
}

$cart = $_SESSION['cart'];

$action = $_GET["action"];
$id	  	= $_GET["id"];
$no	  	= $_GET["no"];
$name   = $_GET["name"];
$price  = $_GET["price"];

switch ($action) {
// ADD TO CART
case "add" :
$_SESSION['cart']->CRT_AddItem($id, $name, $price, $no);
break;	
// DELETE FROM CART
case "delete" :
	$_SESSION['cart']->CRT_DelItem($id);
	break;
}

$_SESSION['cart'] = $cart;
?>
<html>

  <?php print $_SESSION['cart']->CRT_ShowCart(); ?>

</html>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.