This is a simple php code for the shopping cart function that I developed and used. I used a few files to implement the shopping cart without using a database. In this way, if the user closes the browser, all the items in the shopping cart will be deleted. Lost it, friends in need can improve it. It would be better to use database + session + cookie.
The code is as follows |
Copy code |
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;
}
}
html
Insert title here
index.ph
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
|
http://www.bkjia.com/PHPjc/631693.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/631693.htmlTechArticle这是自己开发用到的一个简单的购物车功能的php代码,用了几个文件没用数据库就实现了购物车这样做如果用户关了浏览器,购物车里的商...