Home  >  Article  >  Backend Development  >  PHP shopping cart implementation code_PHP tutorial

PHP shopping cart implementation code_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:24:091583browse

ShopCar.php

Copy code The code is as follows:

class Shopcar
{
//Product list
public $productList=array();
/**
*
* @param unknown_type $product The product passed in
* @return true There is no such product in the shopping cart
*/
public function checkProduct($product)
{
for($i=0 ;$iproductList);$i++ )
{
if($this->productList[$i]['name']==$product['name'] )
return $i;
}
return -1;
}
//Add to cart
public function add($product)
{
$ i=$this->checkProduct($product);
if($i==-1)
array_push($this->productList,$product);
else
$this ->productList[$i]['num']+=$product['num'];
}
//Delete
public function delete($product)
{
$i=$this->checkProduct($product);
if($i!=-1)
array_splice($this->productList,$i,1);
}
//Return all product information
public function show()
{
return $this->productList;
}
}

productList .html
Copy code The code is as follows:





Insert title here



< ;body>

< ;td>Quantity



< td>3
View shopping cart< ;/tr>
Product numberProduct namePricePurchase
0
Buy
1< ;label name='name' >Item 2
Buy
2
Buy
Purchase




index.php
Copy code The code is as follows:

require 'Shopcar.class.php';
session_start();
$name=$_POST['name'];
$num=$_POST['num'];
$price=$_POST['price'];
$product=array('name'=>$name,'num'=>$num,'price'=>$price);
print_r($product);
if(isset($_SESSION['shopcar']))
$shopcar=unserialize($_SESSION['shopcar']);
else
$shopcar=new Shopcar();
$shopcar->add($product);
$_SESSION['shopcar']=serialize($shopcar);

show.php
复制代码 代码如下:










require 'Shopcar.class.php';
session_start();
$shopcar=unserialize($_SESSION['shopcar']);
print_r($shopcar);
$productList=$shopcar->productList;
foreach ($productList as $product){
?>


商品编号商品名称价格数量
1
' />




www.bkjia.comtruehttp://www.bkjia.com/PHPjc/324362.htmlTechArticleShopCar.php 复制代码 代码如下: ?php class Shopcar { //商品列表 public $productList=array(); /** * * @param unknown_type $product 传进来的商品 * @return true 购物车...
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