PHP shopping cart example_PHP tutorial
//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 generate a unique string based on the random number, and finally perform md5 on the string
*/
SetCookie(scid, $session, time() + 14400);
/*
Set the shopping cart cookie
Variable name: scid (I wonder if there is a $ sign missing here? =》Correction: Add "" to scid)
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 item (table name, session, item)
*/
$query = SELECT * FROM $table WHERE session=' $session' AND product=' $product' ;
/*
Look at the 'table' to see if there is the 'product' in the 'shopping cart'
That is, whether the product is Already added to 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, then Return 0
*/
} else {
$row = mysql_fetch_object( $result);
return $row->quantity;
/*
If found, return the Number of items
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 get a certain field in a record, you should use "->" instead of using it like an array. Subscript
*/
}
}
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 and check the class first Has the item been put into the car?
*/
if( $qty == 0) {
$query = INSERT INTO $table (session, product, quantity) VALUES ;
$query . = (' $session', ' $product', ' $quantity') ;
mysql_query( $query);
/*If it is not 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 items of this type 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 quantity of this item For the value in the parameter
*/
}
function clear_cart( $table, $session) {
/*
Clear the shopping cart (nothing to say)
*/
$query = DELETE FROM $table WHERE session=' $session' ;
mysql_query( $query);
}
function cart_total( $table, $session) {
/*
cart Total price of items in
*/
$query = SELECT * FROM $table WHERE session=' $session' ;
$result = mysql_query( $query);
/*
First Take out all items in the car
*/
if(mysql_num_rows( $result) > 0) {
while( $row = mysql_fetch_object( $result)) {
/*
If items If the quantity is > 0 pieces, 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 the 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 information about all items in the car Details
*/
$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 The subscript in the return value array is used to distinguish each item!
*/
$query = SELECT * FROM $table WHERE session=' $session' ORDER BY id ;
$result = mysql_query( $query);
/*
Take out the cart first All items in
*/
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 detailed information about the item into the $contents array
$contents is a two-dimensional array
The first set of subscripts distinguishes different information about each item (such as item name, price, quantity, etc.)
The second set of subscripts distinguishes different items (this This is the function 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, calculate the total price
and put it into the $contents array
*/
return $contents;
/*
Return the array
*/
}
function num_items( $table, $session) {
/*
Returns the total number of item types (that is, it seems nonsense to count two identical items as one - -!)
*/
$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 effects of the operation The number of database rows, 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 things 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)) {
/*
Fetch each item one by one
*/
$quant += $row->quantity; //The quantity of the item is added to the total quantity
}
return $quant; //Return the total quantity
}
}

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

Export password-protected PDF in Photoshop: Open the image file. Click "File"> "Export"> "Export as PDF". Set the "Security" option and enter the same password twice. Click "Export" to generate a PDF file.

Strict types in PHP are enabled by adding declare(strict_types=1); at the top of the file. 1) It forces type checking of function parameters and return values to prevent implicit type conversion. 2) Using strict types can improve the reliability and predictability of the code, reduce bugs, and improve maintainability and readability.

In PHP, the final keyword is used to prevent classes from being inherited and methods being overwritten. 1) When marking the class as final, the class cannot be inherited. 2) When marking the method as final, the method cannot be rewritten by the subclass. Using final keywords ensures the stability and security of your code.

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.
