search
HomeBackend DevelopmentPHP ProblemHow 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.

How to implement shopping cart in php

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/imghwm/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:

How to implement shopping cart in php

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:

How to implement shopping cart in php

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:

How to implement shopping cart in php

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!

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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)