Heim  >  Artikel  >  Backend-Entwicklung  >  php 购物车程序_PHP教程

php 购物车程序_PHP教程

WBOY
WBOYOriginal
2016-07-13 16:55:12878Durchsuche

这是自己开发用到的一个简单的购物车功能的php代码,用了几个文件没用数据库就实现了购物车这样做如果用户关了浏览器,购物车里的商品就会全部丢失哦,有需要的朋友可以改进一下,利用数据库+session +cookie来实现会很好一些。

 代码如下 复制代码

class Shopcar
{
//商品列表
public  $productList=array();

/**
 *
 * @param unknown_type $product 传进来的商品
 * @return true 购物车里面没有该商品
 */
public function checkProduct($product)
{
 
 for($i=0;$iproductList);$i++ )
 {
 
  if($this->productList[$i]['name']==$product['name'])  
  return $i;
 }
 
 return -1;

}
 //添加到购物车
 public function add($product)
{
 $i=$this->checkProduct($product);
 if($i==-1)
 array_push($this->productList,$product);
 else
 $this->productList[$i]['num']+=$product['num']; 
}
//删除
public function delete($product)
{
 $i=$this->checkProduct($product);
 if($i!=-1)
 array_splice($this->productList,$i,1);
 
}

//返回所有的商品的信息
public function show()
{
  return $this->productList;

}


}

html





Insert title here





查看购物车

 


商品编号 商品名称 价格 数量 购买
0
购买
1
购买
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代码,用了几个文件没用数据库就实现了购物车这样做如果用户关了浏览器,购物车里的商...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn