


Code example of how to implement a multi-functional shopping website in PHP
The following editor will bring you a case of implementing a multi-functional shopping website in PHP. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.
1. The page that needs to be implemented:
Index.aspx: Browse the product page and display the product list , users can click "Add to Cart".
ViewCart.aspx: View the shopping cart page, which displays purchased product information. You can click "Delete" and "Submit to add an order to purchase" the product
ViewAccount.aspx: View personal account balance
Login.aspx: Login page
2. Implementation functions:
1. Display product list
2. Implement the purchase function, and dynamically display the quantity of goods in the shopping cart and the total price of the goods when purchasing
3. After clicking to view the shopping cart, the purchased goods will be displayed. Pay attention to the "Purchase Quantity" column. If you click to buy a product multiple times, its "Purchase Quantity" will continue to increase.
4. Delete the purchased items in the shopping cart.
If the "purchase quantity" of a product is 1, when you click "Delete", the product will be deleted directly from the shopping cart;
If the "purchase quantity" of the product is greater than 1 , when you click "Delete" once, the purchase quantity will be reduced by 1. When the purchase quantity of the product reaches 1, and then click Delete, the product will be deleted
5. After viewing the shopping cart, you can also click "Browse Products" to continue purchasing. And the quantity of goods purchased and the total price are displayed above.
6. After "View Shopping Cart", you can submit the order.
But when submitting an order, the following functions must be completed:
(a) Check whether the user is logged in. If not logged in, go to the Login.aspx page
(b) Check whether the user account balance is sufficient for this purchase
(c) Check whether the inventory quantity is sufficient for this purchase
(d) If all the above conditions are met
i. Deduct the total price of this purchase from the user account
ii. Deduct the purchase quantity of each product from the product inventory
iii. Add it to the order table and order content table Add the product information of this purchase
7. Click View Account to view the user’s account balance
The operation code is as follows:
1. First make a login page: loginpage.php
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="bootstrap/js/jquery-1.11.2.min.js"></script> <script src="bootstrap/js/bootstrap.min.js"></script> <link href="bootstrap/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="stylesheet" type="text/css"/> </head> <style> .title{ margin-left: 750px; margin-top: 150px; } .quanju{ margin-left: 650px; margin-top: -460px; } .name,.pwd{ max-width: 120px; } .yangshi1{ margin-top: 200px; } .header{ width: 100%; height: 80px; background: #e0e0e0; } .ps{ margin-left: 100px; margin-top: -100px; } </style> <body> <form class="form-horizontal" role="form" action="dengluchuli.php" method="post"> <p class="header"> <img src="/static/imghwm/default1.png" data-src="img/logo.png" class="lazy" style="max-width:90%" style="max-width:90%" / alt="Code example of how to implement a multi-functional shopping website in PHP" > <p >果 蔬 网</p> </p> <h3 id="用户登录">用户登录</h3> <img class="ps lazy" src="/static/imghwm/default1.png" data-src="./img/果蔬专场.jpg" style="max-width:90%" style="max-width:90%" / alt="Code example of how to implement a multi-functional shopping website in PHP" > <p class="quanju"> <p class="form-group yangshi1"> <label for="firstname" class="col-sm-2 control-label">用户名:</label> <p class="col-sm-10"> <input type="text" class="form-control name" name="uid" placeholder="请输入用户名"> </p> </p> <p class="form-group yangshi2"> <label for="lastname" class="col-sm-2 control-label">密码:</label> <p class="col-sm-10"> <input type="text" class="form-control pwd" name="pwd" placeholder="请输入密码"> </p> </p> <p class="form-group"> <p class="col-sm-offset-2 col-sm-10"> <p class="checkbox"> <label> <input type="checkbox"> 保存密码 </label> <label> <input type="checkbox"> 下次自动登录 </label> </p> </p> </p> <p class="form-group"> <p class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-warning" value="登录" onclick="return login()" > 登录 </button> </p> </p> </p> </form> </body> <script> function login(){ var uid = document.getElementsByTagName("input")[0].value; if(uid==""){ alert("请输入用户名!"); return false; } var pwd = document.getElementsByTagName("input")[1].value; if(pwd==""){ alert("请输入密码!"); return false; } } </script> </html>
The effect is as shown:
2. Create a login processing page: dengluchuli.php
<?php session_start(); $uid = $_POST["uid"]; $pwd = $_POST["pwd"]; require_once "./DBDA.class.php"; $db = new DBDA(); $sql = "select * from login where username='{$uid}'"; $arr = $db->query($sql,0); if($arr[0][2]==$pwd && !empty($pwd)){ $_SESSION["uid"]=$uid; header("location:shopping_list.php"); }else{ echo "登陆失败!"; }
This way you can contact the database. This is the login account of the database. and password, verify the account and password, and then jump to the homepage: shopping_list.php
3. Now make the homepage page: shopping_list.php
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="bootstrap/js/jquery-1.11.2.min.js"></script> <script src="bootstrap/js/bootstrap.min.js"></script> <link href="bootstrap/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="stylesheet" type="text/css"/> </head> <body> <h2 id="水果列表">水果列表</h2> <?php session_start(); //1.找出购物车中多少种商品和总价 $uid = $_SESSION["uid"]; if(empty($_SESSION["uid"])){ header("location:loginpage.php"); exit; } require_once "./DBDA.class.php"; $db = new DBDA(); //如果购物车有商品,取出值 if(!empty($_SESSION["gwd"])){ $arr = $_SESSION["gwd"]; $sum = 0; $numbers = count($arr); foreach($arr as $k=>$v){ //$v[0];//水果名称 //$v[1];//购买数量 $sql = "select * from fruit where ids='{$v[0]}'"; $attr = $db->query($sql,0); $dj = $attr[0][2]; //单价 $sum = $sum+$dj*$v[1]; //总价=单价*数量 } } echo @"<p style='margin-left: 250px'>购物车中商品总数为{$numbers}个,商品总价为:{$sum}元</p>"; ?> <a href="loginpage.php" rel="external nofollow" > 登录 </a> <table class="table table-bordered" > <thead> <tr> <th>代号</th> <th>名称</th> <th>价格</th> <th>产地</th> <th>库存</th> <th>操作</th> </tr> </thead> <tbody> <?php $sql = "select * from fruit"; $arr = $db->query($sql,0); 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='shoppingchuli.php?ids={$v[0]}'>加入购物车</a></td> </tr>"; } ?> </tbody> </table> <a href="add_list.php" rel="external nofollow" >查看购物车</a> </body> </html>
4. Then make the homepage processing page: shoppingchuli.php
##
<?php session_start(); //取到传过来的主键值,并且添加到购物车的SESSION里面 $ids = $_GET["ids"]; //如果是第一次添加购物车,造一个二维数组存到SESSION里面 //如果不是第一次添加,有两种情况 //1.如果该商品购物车里面不存在,造一个一维数组扔到二维里面 //2.如果该商品在购物车存在,让数量加1 if(empty($_SESSION["gwd"])){ //如果是第一次添加购物车,造一个二维数组存到SESSION里面 $arr = array( array($ids,1)); $_SESSION["gwd"]=$arr; }else{ $arr=$_SESSION["gwd"]; if(deep_in_array($ids,$arr)){ //如果该商品在购物车存在,让数量加1 foreach($arr as $k=>$v){ if($v[0]==$ids){ $arr[$k][1]++; } } $_SESSION["gwd"]=$arr; }else{ //如果该商品购物车里面不存在,造一个一维数组扔到二维里面 $arr=$_SESSION["gwd"]; $attr=array($ids,1); $arr[]=$attr; $_SESSION["gwd"]=$arr; } } header("location:shopping_list.php"); function deep_in_array($value, $array) { foreach($array as $item) { if(!is_array($item)) { if ($item == $value) { return true; } else { continue; } } if(in_array($value, $item)) { return true; } else if(deep_in_array($value, $item)) { return true; } } return false; }The effect is as shown:
5. Then view the shopping cart page, you can see the products in the shopping cart, the unit price and the total price: gouwuche.php
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="bootstrap/js/jquery-1.11.2.min.js"></script> <script src="bootstrap/js/bootstrap.min.js"></script> <link href="bootstrap/css/bootstrap.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="stylesheet" type="text/css"/> </head> <?php session_start(); $uid = $_SESSION["uid"]; if(empty($_SESSION["uid"])){ header("location:loginpage.php"); exit; } ?> <body> <h2 id="购物车清单">购物车清单</h2> <table class="table table-bordered" > <thead> <tr> <th>代号</th> <th>名称</th> <th>价格</th> <th>产地</th> <th>购买数量</th> <th>操作</th> </tr> </thead> <tbody> <?php require_once "./DBDA.class.php"; $db = new DBDA(); if(!empty($_SESSION["gwd"])){ $arr = $_SESSION["gwd"]; $sum = 0; $numbers = count($arr); foreach($arr as $k=>$v){ //$v[0];$v[1]; $sql = "select * from fruit where ids='{$v[0]}'"; $a = $db->query($sql,0); //var_dump($v[1]); echo "<tr> <td>{$v[0]}</td> <td>{$a[0][1]}</td> <td>{$a[0][2]}</td> <td>{$a[0][3]}</td> <td>{$v[1]}</td> <td><a href='goodsdel.php?zj={$k}'>删除</a></td> </tr>"; $dj = $a[0][2]; $sum = $sum+$dj*$v[1]; } } //echo "<p style='margin-left: 250px;'>购物车中商品总数为{$numbers}个,商品总价为:{$sum}元</p>"; ?> </tbody> </table> <a href="submit_order.php?ids={$v[0]}" rel="external nofollow" >提交订单</a> </body> </html>The effect is as shown in the figure:
6. Do the deletion processing page goodsdel .php
<?php session_start(); $zj = $_GET["zj"]; //如果该水果数量大于1,减1 //如果该水果数量等于1 移除 $arr = $_SESSION["gwd"]; if($arr[$zj][1]>1){ $arr[$zj][1]=$arr[$zj][1]-1; }else{ unset($arr[$zj]); //清除数组 $arr=array_values($arr); //重新索引数组 } $_SESSION["gwd"] = $arr; header("location:add_list.php");
7.. Then make the submission page: tijiao.php
<?php session_start(); $ids = $_GET["ids"]; //查看余额 $uid = $_SESSION["uid"]; require_once "./DBDA.class.php"; $db = new DBDA(); $sql = "select account from login where username='{$uid}'"; $arr = $db->query($sql,0); $aye = $arr[0][0];//余额 //var_dump($aye); if(!empty($_SESSION["gwd"])){ $arr = $_SESSION["gwd"]; $sum = 0; //$numbers = count($arr); foreach($arr as $v){ $sql = "select * from fruit where ids='{$v[0]}'"; $price = $db->query($sql,0); $dj = $price[0][2]; $sum = $sum+$dj*$v[1]; } }else{ echo "您还未购买商品!"; //header("shopping_list.php"); exit; } //判断余额是否满足购买 if($aye>=$sum){ //判断库存 foreach($arr as $v){ $skc = "select name,numbers from fruit where ids='{$v[0]}'"; $akc = $db->query($sql,0); var_dump($akc); $kc = $akc[0][4];//库存 //var_dump($kc); if($kc<$v[1]){ echo "库存不足!"; exit; } } //提交订单 //账户扣除余额 $skye = "update login set account=account-{$sum} where username='{$uid}'"; $zhye = $db->query($skye); //扣除库存 foreach($arr as $v){ $skckc = "update fruit set numbers=numbers-{$v[1]} where ids='{$v[0]}'"; $sykc = $db->query($skckc); } //添加订单 $ddh = date("Y-m-d H:i:s"); $time = time(); $stjd = "insert into orders values('{$time}','{$uid}','{$ddh}')"; $wcdh = $db->query($stjd); //添加订单详情 foreach($arr as $v){ $ddxq = "insert into orderdetails values('','{$ddh}','{$v[0]}','{$v[1]}')"; $axq = $db->query($ddxq); } }else{ echo "余额不足,请充值!"; exit; } header("location:shopping_list.php");The user account balance has been reduced:
The above is the detailed content of Code example of how to implement a multi-functional shopping website in PHP. For more information, please follow other related articles on the PHP Chinese website!

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
