Php SESSION (Shopping Cart)

Source: Internet
Author: User
Tags php session

SESSION is a common feature in php. We often use it to record global page information. If a user logs on, manages the background, there is also a commonly used shopping cart class, next I will introduce it to you.

SESSION applications in php are essential and one of the most important functions. SESSION is called "SESSION" in network applications ", we usually understand that it stores the information required for a specific user SESSION. In this way, when a user redirects between website pages, the stored SESSION value will not be lost, but will survive throughout the user SESSION. Generally speaking, when user A accesses the internet, it creates an ID (a) value to save it. If your ID (A) value is not canceled, this website will still remember your ID (A) value. At this time, you can call your ID (A) value online. For example, you are welcome to ID () value.

It is very easy to apply the SESSION value in PHP. You only need to input session_start () at the top to start the SESSION. Now you can use the SESSION. This is only an application method for small websites, in fact, the SESSION itself has many attributes, such as SESSION cycle, SESSION call, SESSION data validity period, SESSION storage, and SESSION cancellation. If these attributes are available, it seems to be a relatively standard SESSION application SESSION.

The following is a complete Session class that integrates the most basic attribute values of a Session. opening, closing, and cleaning are in line with php programming specifications, which is also a good habit. For a small note, if the website does not use a large number of Session classes, it is basically unnecessary to use the SESSION class.

The Code is as follows: Copy code


<? Php
/**
* File description Session class
* ===================================================== ======================================
* File name session. class. php
*-----------------------------------------------------------------
* Applicable environment: PHP5.2.x/mysql 5.0.x
*-----------------------------------------------------------------
* Author 04ie. Com
*-----------------------------------------------------------------
* Creation Time: 2010-2-1
* ===================================================== ======================================
*/
Class Session
{
/**
* Default session Validity Period
* @ Access public
* @ Var ineger $ _ expiry
*/
Public $ _ expiry = 3600;
/**
* Valid Domain Name
* @ Access public
* @ Var string $ _ domain
*/
Public $ _ domain = '.phpfamily.cn ';
// Initialization
Public function _ construct ()
{
Ini_set ('session. use_trans_id ', 0 );
Ini_set ('session. gc_maxlifetime', $ this-> _ expiry );
Ini_set ('session. use_cookie ', 1 );
Ini_set ('session. cookie_path ','/');
Ini_set ('session. cookie_domain ', $ this-> _ domain );
Session_module_name ('user ');
Session_set_save_handler (
Array (& $ this, 'open '),
Array (& $ this, 'close '),
Array (& $ this, 'read '),
Array (& $ this, 'write '),
Array (& $ this, 'deststroy '),
Array (& $ this, 'gc ')
);
Session_start ();
}
/**
* Open a session
* @ Access public
* @ Param string $ savePath
* @ Param string $ sName
* @ Return true
*/
Public function open ($ savePath, $ sName)
{
$ This-> _ conn = mysql_connect ('localhost', 'root ','');
Mysql_select_db ('databases ');
Mysql_query ('set NAMES "utf8 "');
Return true;
}
/**
* Close the session
* @ Access public
* @ Return bool
*/
Public function close ()
{
Return mysql_close ($ this-> _ conn );
}
/**
* Read session
* @ Access public
* @ Param string $ sid sessionID
* @ Return mixed
*/
Public function read ($ sid)
{
$ SQL = "SELECT data FROM sessions WHERE sessionid = '% S '";
$ SQL = sprintf ($ SQL, $ sid );
$ Res = mysql_query ($ SQL, $ this-> _ conn );
$ Row = mysql_fetch_assoc ($ res );
Return! $ Row? Null: $ row ['data'];
}
/**
* Write session
* @ Access public
* @ Param string $ sid sessionID
* @ Param string $ data serialize the serialized session content
* @ Return
*/
Public function write ($ sid, $ data)
{
$ Expiry = time () + $ this-> _ expiry;
$ SQL = "REPLACE INTO sessions (sessionid, expiratio
N, data) VALUES ('% s',' % d', '% s ')";
$ SQL = sprintf ($ SQL, $ sid, $ expiry, $ data );
Mysql_query ($ SQL, $ this-> _ conn );
Return true;
}
/**
* Destroy a session
* @ Access public
* @ Param string $ sid sessionID
* @ Return
*/
Public function destroy ($ sid)
{
$ SQL = "DELETE FROM sessions WHERE sessionid = '% S '";
$ SQL = sprintf ($ SQL, $ sid );
Mysql_query ($ SQL, $ this-> _ conn );
Return true;
}
/**
* Clear expired sessions
* @ Access public
* @ Param integer $ time
* @ Return
*/
Public function gc ($ time = 0)
{
$ SQL = "DELETE FROM sessions WHERE expiration <'% d '";
$ SQL = sprintf ($ SQL, time ());
Mysql_query ($ SQL, $ this-> _ conn );
Mysql_query ('optimize TABLE session ');
Return true;
}
 

Next let's look at a php session shopping cart class.

The Code is as follows: Copy code

<? Php
Class Cart {
Public function Cart (){
If (! Isset ($ _ SESSION ['cart']) {
$ _ SESSION ['cart'] = array ();
}
}

/*
Add Product
Param int $ id commodity primary key
String $ name product name
Float $ price
Int $ num shopping quantity
*/
Public function addItem ($ id, $ name, $ price, $ num, $ img ){
// If the product already exists, add the quantity directly.
If (isset ($ _ SESSION ['cart'] [$ id]) {
$ This-> incNum ($ id, $ num );
Return;
}
$ Item = array ();
$ Item ['id'] = $ id;
$ Item ['name'] = $ name;
$ Item ['price'] = $ price;
$ Item ['num'] = $ num;
$ Item ['img '] = $ img;
$ _ SESSION ['cart'] [$ id] = $ item;
}

/*
Modify the quantity of items in the shopping cart
Int $ id commodity primary key
Int $ num: the number of modified items.
Change the quantity to $ num.
*/
Public function modNum ($ id, $ num = 1 ){
If (! Isset ($ _ SESSION ['cart'] [$ id]) {
Return false;
}
$ _ SESSION ['cart'] [$ id] ['num'] = $ num;
}

/*
Product Quantity + 1
*/
Public function incNum ($ id, $ num = 1 ){
If (isset ($ _ SESSION ['cart'] [$ id]) {
$ _ SESSION ['cart'] [$ id] ['num'] + = $ num;
}
}

/*
Item quantity-1
*/
Public function decNum ($ id, $ num = 1 ){
If (isset ($ _ SESSION ['cart'] [$ id]) {
$ _ SESSION ['cart'] [$ id] ['num']-= $ num;
}

// If the quantity is 0 after the decrease, delete the item
If ($ _ SESSION ['cart'] [$ id] ['num'] <1 ){
$ This-> delItem ($ id );
}
}

/*
Delete item
*/
Public function delItem ($ id ){
Unset ($ _ SESSION ['cart'] [$ id]);
}
 
/*
Obtain a single item
*/
Public function getItem ($ id ){
Return $ _ SESSION ['cart'] [$ id];
}

/*
Query the types of items in the shopping cart.
*/
Public function getCnt (){
Return count ($ _ SESSION ['cart']);
}
 
/*
Query the number of items in the shopping cart.
*/
Public function getNum (){
If ($ this-> getCnt () = 0 ){
// The number is 0, and the number is also 0
Return 0;
}

$ Sum = 0;
$ Data = $ _ SESSION ['cart'];
Foreach ($ data as $ item ){
$ Sum + = $ item ['num'];
}
Return $ sum;
}

/*
Total amount of items in the shopping cart
*/
Public function getPrice (){
// The quantity is 0 and the price is 0.
If ($ this-> getCnt () = 0 ){
Return 0;
}
$ Price = 0.00;
Foreach ($ this-> items as $ item ){
$ Price + = $ item ['num'] * $ item ['price'];
}
Return sprintf ("% 01.2f", $ price );
}

/*
Clear shopping cart
*/
Public function clear (){
$ _ SESSION ['cart'] = array ();
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.