Jump to content

php shopping cart, database or session?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
Jacki

Jacki

    Learning Programmer

  • Members
  • PipPipPip
  • 80 posts
Hi,
I'm programming a shopping cart with php but i'm not sure if it's better to use session or database to save the items in the cart (cart is a class in my code). What do you advise me? Maybe the sessions are better because a guest can also put his items in his cart...

Thanks in advance... bye...^^
Posted Image

Posted Image

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
I would store data in the database. Sessions will still be important, however, for managing the database access.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
Jacki

Jacki

    Learning Programmer

  • Members
  • PipPipPip
  • 80 posts
This is my actual Cart:
class Cart

{

	private $items;

	

	public function __construct()

	{

		if(!isset($_SESSION['items']))

			$this->items = array();

		else 

			$this->items = $_SESSION['items'];

	}

	

	public function __destruct()

	{

		$_SESSION['items'] = $this->items;

	}

	

	public function add_item($id, $num)

	{

		if($num > 0)

			$this->items[$id] += $num;

		else

			$this->items[$id] = 0;

	}	

	

	public function show_items()

	{

		return $this->items;

	}

}
I think that the sessions are more convenient because a guest can fill the cart while he is unregistered.. What do you think?
Posted Image

Posted Image

#4
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
To check out, I would still want the person to be registered.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#5
gakattack

gakattack

    Newbie

  • Members
  • Pip
  • 6 posts
You could always make it session only if the user isn't logged in, and database-based otherwise. I assume they need to register at some point though to purchase something, at that point you can throw it into a database from the session variables.

If you're selling stuff online; it's always good to have records!
Well, that's what I would do.

#6
gakattack

gakattack

    Newbie

  • Members
  • Pip
  • 6 posts
I could be wrong, but I think a properly designed database would be easier on the server than loads of session variables per user.