How to implement shopping cart in php
How to implement the shopping cart in php: 1. Lay out the front-end page; 2. Put the purchased item into a one-dimensional array; 3. Put all the one-dimensional arrays into a In a two-dimensional array; 4. Put the corresponding data into the session.
The operating environment of this article: Windows7 system, PHP7.1 version, DELL G3 computer
php realizes the shopping cart function
First lay out the front-end page layout as follows:
<?php $conn=mysql_connect("localhost","root",""); mysql_select_db("shop",$conn); mysql_query("set names gb2312"); $sql="select * from produce"; //查询所有商品 $rs=mysql_query($sql,$conn); //执行sql语句,得到一个结果集 while($row=mysql_fetch_array($rs)) //遍历结果集 { ?> <table width="343" height="152" border="1" style="float:left"> <tr> <td width="124" rowspan="3"><img src="/static/imghw/default1.png" data-src="images/<?php echo $row[" class="lazy"pimg"]? alt="How to implement shopping cart in php" >" width="123" style="max-width:90%" border="0" /></td> <td width="203" height="35">货物名称:<?php echo $row["pname"] ?></td> </tr> <tr> <td height="28">货物价格:<?php echo $row["price"] ?></td> </tr> <tr> <td height="27" align="center"><a href="buy.php?id=<?php echo $row["pid"] ?>&pname=<?php echo $row["pname"] ?>">购买</a></td> </tr> </table> <?php } ?>
View page effect:
We can Put the purchased item into a one-dimensional array, then put all the one-dimensional arrays into a two-dimensional array, and finally put the two-dimensional array into the session. No matter how you modify the purchased items in the future, you can take them out of the session and modify them.
<?php session_start();//使用session之前一定要将session开启 ob_start();//要清空缓存就必须ob_start() $pid=$_GET["id"];//得到购买物品的id $name=$_GET["pname"];//得到购买物品的名字 $arr=$_SESSION["mycar"];//将session中的变量取出来 //下面先判断这个变量是否是数组,可以得到以前是否买过东西 if(is_array($arr)){ //如果是数组,说明以前买过东西 //如果买过东西又分两种情况: if(array_key_exists($pid,$arr)){ //1、array_key_exists($pid,$arr)判断$arr中是否存在键值为$pid的一个一维数组,如果存在的话,就说明此商品以前购买过,只需要把数量加1 $uu=$arr[$pid]; //从二维数组里拿出对应的一维数组,该一维数组包括id name num 三个值 $uu["num"]=$uu["num"]+1; //改变数量,将数量加1 $arr[$pid]=$uu; //改完后再将此一维数组放回二维数组中 }else{ //2.此商品第一次购买,就将得到的id和name值组成一个一维数组 $arr[$pid]=array("pid"=>$pid,"name"=>$name,"num"=>1); } }else{ $arr[$pid]=array("pid"=>$pid,"name"=>$name,"num"=>1); } $_SESSION["mycar"]=$arr; //购买完后,将此数组重新放入session中,便可以在各个页面看到此session ob_clean();//清空缓存 header("location:car.php");//跳转到购物车界面(car.php) ?>
Shopping cart code:
<?php session_start();//启用session $arr=$_SESSION["mycar"];//从session中拿出二维数组 ?> <form> //下面将数组里的数据即客户所购买的物品展示出来 <table width="600" height="37" border="1"> <tr> <td width="96">商品ID</td> <td width="158">商品名称</td> <td width="154">商品数量</td> <td width="177">删除</td> </tr> <?php //遍历这个二维数组 foreach($arr as $a){ ?> <tr> <td width="96"><?php echo $a["pid"] ?></td>//物品的id <td width="158"><?php echo $a["name"] ?></td>//物品的名称 <td width="154"><?php echo $a["num"] ?></td>//物品的数量 <td width="177"><a href="delete.php?id=<?php echo $a[pid] ?>">删除</a></td>//点击删除超链接到”delete.php”,将物品的id传过去 </tr> <?php } ?> </table> </form> <a href="index.php">返回继续购物</a>//返回到首页
Page effect:
When deleting a product, first get the id of the product to be deleted. After getting the id, take out the one-dimensional array corresponding to the obtained id in the two-dimensional array, clear the one-dimensional array (unset()), and then put the two-dimensional array back into session(),
<?php session_start();//启动session ob_start();//清空缓存必须启动的项 $pid=$_GET["id"];//得到通过get方式传过来的id $arr=$_SESSION["mycar"];//拿出session里的二维数组 foreach($arr as $key=>$proId)//遍历该二维数组中的键值,这里也就是商品的id { if($key==$pid)//判断键值等于传过来的商品id { unset($arr[$key]);//清除该一维数组 } } $_SESSION["mycar"]=$arr;//将清除之后的二维数组重新放到session里 ob_clean();//清除缓存 header("location:car.php");//跳转到购物车 ?>
The effect of deleting an item:
The function of the shopping cart is implemented as follows: purchase the product to get the id and name of the product, and add these two values The previous quantity (1) is put into a one-dimensional array. One product is a one-dimensional array, so it is natural to use a two-dimensional array for so many products. Before that, check whether the product has been purchased before. If so, add one to the previous quantity. Otherwise, re-create a one-dimensional array and put the one-dimensional array into a two-dimensional array. Finally put it into the session. When deleting, get the ID of the product to be deleted, then find the one-dimensional array that stores the product from the two-dimensional array, clear the one-dimensional array, and then put the two-dimensional array into the session. In this way, a simple shopping cart function similar to the one above is implemented.
This is just a simple implementation of the shopping cart function
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to implement shopping cart in php. For more information, please follow other related articles on the PHP Chinese website!

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



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
