Table of Contents
The specific analysis is as follows:
登入页面
长腿璇购物商城
查看购物车
Home Backend Development PHP Problem How to implement the php shopping cart function

How to implement the php shopping cart function

Sep 01, 2020 am 10:00 AM
php shopping cart

How to implement the shopping cart function in php: first log in to the website to browse the products; then purchase the specified products; then enter the shopping cart page, where you can change the number of products, delete products, clear the shopping cart, Continue shopping and so on; finally, you can generate an order, submit an order and other operations.

How to implement the php shopping cart function

Recommended: "PHP Video Tutorial"

Introducing a shopping cart code and ideas implemented in PHP , the functions are fully realized and have certain reference value.

Here we provide you with a simple php shopping cart code, from adding shopping products to making purchases. In mall development, this function is indispensable.

The specific analysis is as follows:

1. The operations on the products in the shopping cart generally include the following:

Add products, delete products, And submit the order;

2. The essence of the method is:

Store the session in the array, add, delete, and modify the array. Each group in the array The records are all information about a product (number, price, etc.);

3. The idea of ​​​​solving the shopping cart is to use session to record a two-dimensional array.

One dimension represents each product, and the two dimensions include the product ID, the quantity of the product, etc. You can add it by yourself. Anyway, it is two dimensions. You can add as many product attributes as you want.

4. Shopping cart operation process:

First, log in to the website to browse the products; then, purchase the specified products and enter the shopping cart page. The page can change the quantity of goods, delete goods, clear the shopping cart, continue shopping, etc.; finally, generate orders, submit orders and other operations.

Please see the powerful comments for details;

Log in first;

<body>
<h1 id="登入页面">登入页面</h1>
<form action="dengrucl.php" method="post">
    <p>帐号:<input type="text" name="zhang"/></p>
    <p>密码:<input type="text" name="mi"/></p>
    <input type="submit" value="登入"/>
</form>

</body>复制代码
Copy after login

How to implement the php shopping cart function

Login processing:

<?php
session_start();
include ("db.class.php");$db = new db();$zhang = $_POST["zhang"];$mi = $_POST["mi"];$sql = "select mi from yonghu WHERE zhang = &#39;{$zhang}&#39;";$arr = $db->Query($sql);if(!empty($zhang)&&!empty($mi)&&$mi = $arr){    $_SESSION["zhang"] = $zhang;
    header("location:zym.php");
}else{    echo "登入失败";
}

?>复制代码
Copy after login

It’s a very simple login, nothing to say;

After logging in, he will go directly to the main page:

<body>
<h1 id="长腿璇购物商城">长腿璇购物商城</h1>
<table border="1" cellpadding="0" cellspacing="0" width="100%" >
    <tr>
        <td>代号</td>
        <td>水果名称</td>
        <td>水果价格</td>
        <td>水果产地</td>
        <td>水果库存</td>
        <td>操作</td>
    </tr>复制代码
Copy after login
 <?php
    session_start();$_SESSION["zhang"] = "xiaoming";//不做登入的情况下,直接存sessiion
    include ("db.class.php");    $db = new db();    $sql = "select * from sgbiao";    $arr = $db->Query($sql);
    foreach ($arr as $v)
    {        echo " <tr>
        <td>{$v[0]}</td>
        <td>{$v[1]}</td>
        <td>{$v[2]}</td>
        <td>{$v[3]}</td>
        <td>{$v[4]}</td>
        <td>
        <a href=&#39;zymcl.php?ids={$v[0]}&#39;>加入购物车</a>
</td>
    </tr>";
    }

    ?>
    <?php
    //这里显示的是 购物车有多少产品,和产品的总价格    $ann=array();    if(!empty($_SESSION["gwc"]))
    {        $ann=$_SESSION["gwc"];

    }    $zhonglei = count($ann);    $aa=0;
    foreach($ann as $k)
    {        $k[0];//水果代号        $k[1];//水果数量        $sql1="select jiage from sgbiao where ids=&#39;{$k[0]}&#39;";        $danjia=$db->Query($sql1);

        foreach($danjia as $n)
        {            $aa=$aa + $n[0]*$k[1];
        }


    }    echo"数量:{$zhonglei}<br/>
价格:<mark>{$aa}元";
    ?>
复制代码
复制代码
</table>

<a href="tijiao.php">查看账户</a>
<a href="ckgwc.php">查看购物车</a>

</body>复制代码
Copy after login

Pictures coming:

How to implement the php shopping cart function

When I click add to the shopping cart:

How to implement the php shopping cart function

The quantity and price above have changed, indicating that it has been added to the shopping cart;

Let’s take a look at how it is handled (powerful comments):

<?php
session_start();
//$ids = $_GET["ids"];if(empty($_SESSION["gwc"]))
{
    //如果点击的购物车是空的(第一次添加)

    //如果购物车里是空的,造二维数组,    $arr = array(
        array($ids,1)
        //一维数组,取ids,第一次点击增加一个
    );    $_SESSION["gwc"]=$arr;
    //扔到session里面
}else
    //这里不是第一次点击
{
    //先判断购物车里是否已经有了该商品,用$ids
    $arr = $_SESSION["gwc"];
    //把购物车的状态取出来    $chuxian = false;
//定义一个变量;用来表示是否出现,默认是未出现
    foreach ($arr as $v) {
        //便利他
        //如果这里面有这件商品        if ($v[0] == $ids) //如果取过来的$v[0](商品的代号)等于$ids那么就证明购物车中已经有了这一件商品
        {            $chuxian = true;
            //如果出现,直接把chuxian改成true

        }
    }    if($chuxian)
    {
        //购物车中有此商品        for($i=0;$i<count($arr);$i++)
        {            if($arr[$i][0] == $ids)
            {
                //把点到的商品编号加1                $arr[$i][1] += 1;
            }
        }        $_SESSION["gwc"] = $arr;

    }        else
            {
                //这里就只剩下:购物车里有东西,但是并没有这件商品                $asg = array($ids,1);
                //设一个小数组                $arr[] = $asg;                $_SESSION["gwc"]=$arr;
            }

}
header("location:zym.php")


?>复制代码
Copy after login

Next, let’s make the shopping cart page:

<body>
<h1 id="查看购物车">查看购物车</h1>
<table width="100%" border="1"cellspacing="0" cellpadding="0">
    <tr>
        <td>商品名称</td>
        <td>商品单价</td>
        <td>商品数量</td>
        <td>操作</td>
    </tr>复制代码
Copy after login
 <?php
    session_start();    if(!empty($_SESSION["gwc"]))
    {        $arr = array();        $arr = $_SESSION["gwc"];
        //造数组
    }
    include (&#39;db.class.php&#39;);    $db = new db();
    foreach ($arr as $v)
    {
        global $db;        $sql = "select * from sgbiao WHERE ids = &#39;{$v[0]}&#39;";        $att = $db->query($sql);
        foreach ($att as $a)
        {            echo "<tr>
        <td>{$a[1]}</td>
        <td>{$a[2]}</td>
        <td>{$v[1]}</td>
        <td><a href=&#39;shanchu.php?ids={$a[0]}&#39;>删除</a> </td>
    </tr> ";
//            蔬果的名称
//            单价
//            取int数量
//        这个地方也可以加索引shanchu.php?sy={$v}
        }
    }
    ?>
</table>

<a href="tijiao.php">提交订单</a>
</body>复制代码
Copy after login

Above picture:

How to implement the php shopping cart function

You can see that the number of big apples is 4. If I click delete, the condition is that there are big apples and the number is greater than one. Click delete to reduce the number by one:

White Grape The number is 1. If I click delete, the condition is that the number is not greater than one, so that it can be removed from the array;

Come and take a look at the delete page:

<?php
session_start();$ids = $_GET["ids"];$arr = $_SESSION["gwc"];
//var_dump($arr);
//取索引2(数量)
foreach ($arr as $key=>$v)
{    if($v[0]==$ids)
    {        if($v[1]>1){
            //要删除的数据           $arr[$key][1]-=1;
        }        else{
            //数量为1的情况下,移除该数组            unset($arr[$key]);
        }
    }

}$_SESSION["gwc"] = $arr;
//记得扔到session里面
header("location:ckgwc.php");
//删除完跳转回去复制代码
Copy after login

High energy! !

Submit order page, there is only one processing page, if you need, you can fill in the link yourself:

<?php
session_start();
include ("db.class.php");$db = new db();

//判断用余额是否满足$zhang = $_SESSION["zhang"];
//获取到用户名$sye = "select zhanghu from yonghu WHERE zhang = &#39;{$zhang}&#39;";$ye = $db->query($sye);$ye[0][0];//这是余额$ann=array();if(!empty($_SESSION["gwc"]))
{    $ann=$_SESSION["gwc"];

}$zhonglei = count($ann);$aa=0;//总价格
foreach($ann as $k)
{    $k[0];//水果代号    $k[1];//水果数量    $sql1="select jiage from sgbiao where ids=&#39;{$k[0]}&#39;";    $danjia=$db->Query($sql1);

    foreach($danjia as $n)
    {        $aa=$aa + $n[0]*$k[1];
    }


}
//判断余额是否满足if($ye[0][0]>=$aa)
{
    //钱够,判断库存

    foreach($ann as $v)
    {        $skc = "select sgname,kucun from sgbiao WHERE ids=&#39;{$v[0]}&#39;";
        //水果代号$v[0]        $akc = $db->query($skc);        $akc[0][1];//库存
        //比较是否满足库存        if($akc[0][1]<$v[1])
        {            echo "{$akc[0][0]}库存不足";
            //退出            exit;
        }

    }
//提交订单:
//i.    从用户账户中扣除本次购买的总价格
//ii.    从商品库存中扣除本次每种商品的购买数量
//iii.    向订单表和订单内容表中加入本次购买的商品信息
    //扣除账户余额$skcye = "update yonghu set zhanghu = zhanghu-{$aa} WHERE zhang = &#39;{$zhang}&#39;";    $db->query($skcye,0);
    //扣除库存
    foreach($ann as $v)
    {        $skckc = "update sgbiao set kucun = kucun-{$v[1]} WHERE ids=&#39;{$v[0]}&#39;";
        //水果代号$v[0]        $db->query($skckc,0);
    }
    //添加订单信息
    //取当前时间    $time = time();
    //自动生成订单号    $ddh = date("YmdHis");    $sdd = "insert into dingdan VALUES (&#39;{$ddh}&#39;,&#39;$zhang&#39;,&#39;$time&#39;)";    $db->query($sdd,0);
    //添加订单内容
    foreach ($ann as $v)
    {        $sddxq = "insert into ddneirong VALUES (&#39;&#39;,&#39;$ddh&#39;,&#39;{$v[0]}&#39;,&#39;{$v[1]}&#39;)";        $db->query($sddxq,0);
    }


}else{    echo "钱不够";    exit;
}复制代码
Copy after login

In this way, the general functions of the shopping cart have been realized;

Let’s take a look at the effect after clicking to submit the order:

1. Reduce fruit inventory:

How to implement the php shopping cart function

2. Add Order:

How to implement the php shopping cart function

3. Add order content:

How to implement the php shopping cart function

4. Deduct the purchaser’s account balance:

How to implement the php shopping cart function


The above is the detailed content of How to implement the php shopping cart function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

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

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles