search
HomeBackend DevelopmentPHP Tutorialphp mysql shopping cart implementation program_PHP tutorial

php mysql shopping cart implementation program_PHP tutorial

Jul 13, 2016 pm 04:55 PM
mysqlphpphp+mysqlcodebased onaccomplisharticleyeshaveofprogramshopping cart

This article is a shopping cart code from the Internet, which is based on php+mysql. Students in need can take a look. I also recommend a variety of shopping cart methods below. Students in need can take a look at these shopping carts. Is the code available to you?

The code is as follows Copy code
Simple and easy to understand. The cookie stores the shopping cart ID, and the db stores the shopping cart data.
//Shopping cart session generation code
if(! $session && ! $scid) {
/*
Session is used to distinguish each shopping cart, which is equivalent to the ID number of each cart;
scid is only used to identify a shopping cart ID number, which can be regarded as the name of each cart;
When both the id and session value of the shopping cart do not exist, a new shopping cart is generated
*/
$session = md5(uniqid(rand()));
/*
Generate a unique shopping cart session number
rand() first generates a random number, uniqid() then generates a unique string based on the random number, and finally performs md5 on the string
*/
SetCookie(scid, $session, time() + 14400);
/*
Set this shopping cart cookie
Variable name: scid (I wonder if there is a $ sign missing here? =》Correction: scid needs to add "")
Variable value: $session
Valid time: current time + 14400 seconds (within 4 hours)
For detailed usage of the setcookie function, please refer to the PHP manual~
*/
}
class Cart { //Start shopping cart class
function check_item( $table, $session, $product) {
/*
Check items (table name, session, item)
*/
$query = SELECT * FROM $table WHERE session=' $session' AND product=' $product' ;
/*
Check if the 'product' is in the 'shopping cart' in the 'table'
That is, has the product been put into the shopping cart
*/
$result = mysql_query( $query);
if(! $result) {
return 0;
}
/*
Query failed
*/
$numRows = mysql_num_rows( $result);
if( $numRows == 0) {
return 0;
/*
If not found, return 0
*/
} else {
$row = mysql_fetch_object( $result);
return $row->quantity;
/*
If found, return the item quantity
It is necessary to explain the mysql_fetch_object function (will be used below):
[mysql_fetch_object() is similar to mysql_fetch_array(), with one difference - it returns an object instead of an array. 】
The above sentence is taken from the php manual, it should be very clear ~
To put it simply, to retrieve a certain field in a record, you should use "->" instead of using subscripts like an array
*/
}
}
function add_item( $table, $session, $product, $quantity) {
/*
Add new item (table name, session, item, quantity)
*/
$qty = $this->check_item( $table, $session, $product);
/*
Call the above function to first check whether the item has been put into the car
*/
if( $qty == 0) {
$query = INSERT INTO $table (session, product, quantity) VALUES ;
$query .= (' $session', ' $product', ' $quantity') ;
mysql_query( $query);
/*If there is no such item in the car, add the item to the car*/
} else {
$quantity += $qty; //If there is, increase the quantity on the original basis
$query = UPDATE $table SET quantity=' $quantity' WHERE session=' $session' AND ;
$query .= product=' $product' ;
mysql_query( $query);
/*
and modify the database
*/
}
}
function delete_item( $table, $session, $product) {
/*
Delete item (table name, session, item)
*/
$query = DELETE FROM $table WHERE session=' $session' AND product=' $product' ;
mysql_query( $query);
/*
Delete this type of item in the shopping cart
*/
}
function modify_quantity( $table, $session, $product, $quantity) {
/*
Modify item quantity (table name, session, item, quantity)
*/
$query = UPDATE $table SET quantity=' $quantity' WHERE session=' $session' ;
$query .= AND product=' $product' ;
mysql_query( $query);
/*
Modify the item quantity to the value in the parameter
*/
}
function clear_cart( $table, $session) {
/*
Clear shopping cart (nothing to say)
*/
$query = DELETE FROM $table WHERE session=' $session' ;
mysql_query( $query);
}
function cart_total( $table, $session) {
/*
Total price of items in the car
*/
$query = SELECT * FROM $table WHERE session=' $session' ;
$result = mysql_query( $query);
/*
Take out all the items in the car first
*/
if(mysql_num_rows( $result) > 0) {
while( $row = mysql_fetch_object( $result)) {
/*
If the number of items > 0, then judge the price one by one and calculate
*/
$query = SELECT price FROM inventory WHERE product=' $row->product' ;
$invResult = mysql_query( $query);
/*
Find the price of this item from the inventory table
*/
$row_price = mysql_fetch_object( $invResult);
$total += ( $row_price->price * $row->quantity);
/*
Total price += price of the item * quantity of the item
(Everyone should be able to understand it:) )
*/
}
}
return $total; //Return the total price
}
function display_contents( $table, $session) {
/*
Get detailed information about everything in your car
*/
$count = 0;
/*
Item quantity count
Note that this variable is not only used to count the number of items, but more importantly, it will be used as a subscript in the return value array to distinguish each item!
*/
$query = SELECT * FROM $table WHERE session=' $session' ORDER BY id ;
$result = mysql_query( $query);
/*
Take out all the items in the car first
*/
while( $row = mysql_fetch_object( $result)) {
/*
Get detailed information for each item separately
*/
$query = SELECT * FROM inventory WHERE product=' $row->product' ;
$result_inv = mysql_query( $query);
/*
Find information about this item from the inventory table
*/
$row_inventory = mysql_fetch_object( $result_inv);
$contents[product][ $count] = $row_inventory->product;
$contents[price][ $count] = $row_inventory->price;
$contents[quantity][ $count] = $row->quantity;
$contents[total][ $count] = ( $row_inventory->price * $row->quantity);
$contents[description][ $count] = $row_inventory->description;
/*
Put all the details about the item into the $contents array
$contents is a two-dimensional array
The first set of subscripts is to distinguish the different information of each item (such as item name, price, quantity, etc.)
The second set of subscripts is to distinguish different items (this is the role of the $count variable defined earlier)
*/
$count++; //The number of items plus one (i.e. the next item)
}
$total = $this->cart_total( $table, $session);
$contents[final] = $total;
/*
At the same time, call the cart_total function above to calculate the total price
and put it into the $contents array
*/
return $contents;
/*
Return this array
*/
}
function num_items( $table, $session) {
/*
Returns the total number of item types (that is, two identical items are counted as one type, which seems like nonsense - -!)
*/
$query = SELECT * FROM $table WHERE session=' $session' ;
$result = mysql_query( $query);
$num_rows = mysql_num_rows( $result);
return $num_rows;
/*
Take out all the items in the car and get the number of database rows affected by the operation, that is, the total number of items (nothing to say)
*/
}
function quant_items( $table, $session) {
/*
Returns the total number of all items (that is, two identical items are also counted as two items - -#)
*/
$quant = 0;//Total quantity of items
$query = SELECT * FROM $table WHERE session=' $session' ;
$result = mysql_query( $query);
while( $row = mysql_fetch_object( $result)) {
/*
Take out each item one by one
*/
$quant += $row->quantity; //The quantity of the item is added to the total quantity
}
return $quant; //Return the total amount
}
}

The following is the content about the shopping cart

http://www.bKjia.c0m/phper/22/33260.htm
http://www.bKjia.c0m/phper/php/40196.htm
http://www.bKjia.c0m/phper/php-gj/35504.htm
http://www.bKjia.c0m/phper/php-gj/34552.htm
http://www.bKjia.c0m/phper/22/33260.htm
http://www.bKjia.c0m/phper/php-gj/33948.htm
http://www.bKjia.c0m/phper/php-gj/39684.htm

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631642.htmlTechArticleThis article is a shopping cart code from the Internet, based on php+mysql. Students in need can read it See below I also recommend a variety of shopping cart methods. Students in need can take a look...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool