Home >Backend Development >PHP Tutorial >php shopping cart program_PHP tutorial

php shopping cart program_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 16:55:12934browse

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








查看购物车

 


Product numberProduct namePriceQuantity Buy
0

Buy
1

Buy
2
购买
3
购买



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










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/631693.htmlTechArticle这是自己开发用到的一个简单的购物车功能的php代码,用了几个文件没用数据库就实现了购物车这样做如果用户关了浏览器,购物车里的商...
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