php+pdo实现的购物车类完整示例
本文实例讲述了php+pdo实现的购物车类。分享给大家供大家参考,具体如下:
pdo=newPDO("mysql:host=$host;dbname=$db","$user","$pwd",array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));
$this->pdo->query("setnamesutf8");
}catch(PDOException$e){
echo$e->getMessage();
}
}
//添加商品到购物车
publicfunctionadd_cart($productid,$num)
{
$sql="selectpricefromshop_productwhereid=?";
$stmt=$this->pdo->prepare($sql);
$stmt->execute(array($productid));
$data=$stmt->fetch(PDO::FETCH_ASSOC);
$price=$data['price'];
$createtime=time();
$sql="select*fromshop_cartwhereproductid=?anduserid=?";
$stmt=$this->pdo->prepare($sql);
$stmt->execute(array($productid,$_SESSION['user_id']));
$data=$stmt->fetch(PDO::FETCH_ASSOC);
if($data){
$sql="updateshop_cartsetnum=num+?whereuserid=?andproductid=?";
$params=array($num,$_SESSION['user_id'],$productid);
}else{
$sql="insertintoshop_cart(productid,num,userid,price,createtime)values(?,?,?,?,?)";
$params=array($productid,$num,$_SESSION['user_id'],$price,$createtime);
}
$stmt=$this->pdo->prepare($sql);
$stmt->execute($params);
$rows=$stmt->rowCount();
return$rows?
show(1,'ok',$rows):
show(0,'fail');
}
//修改购买数量
publicfunctionchange_num($productid,$num)
{
$sql="updateshop_cartsetnum=?whereuserid=?andproductid=?";
$stmt=$this->pdo->prepare($sql);
$stmt->execute(array($num,$_SESSION['user_id'],$productid));
$rows=$stmt->rowCount();
return$rows?
show(1,'ok',$rows):
show(0,'fail');
}
//清空购物车
publicfunctionclear_cart()
{
$sql="deletefromshop_cartwhereuserid=?";
$stmt=$this->pdo->prepare($sql);
$this->pdo->execute(array($this->user_id));
$rows=$stmt->rowCount();
return$rows?
show(1,'ok',$rows):
show(0,'fail');
}
//从购物车中删除商品
publicfunctionremove_cart($productid)
{
$sql="deletefromshop_cartwhereproductid=?anduserid=?";
$stmt=$this->pdo->prepare($sql);
$stmt->execute(array($productid,$_SESSION['user_id']));
$rows=$stmt->rowCount();
return$rows?
show(1,'ok',$rows):
show(0,'fail');
}
}
//处理数据
functionshow($status,$message,$data=array())
{
$result=array(
'status'=>$status,
'message'=>$message,
'data'=>$data
);
exit(json_encode($result));
}
//简单使用
$user=[
'host'=>'',
'user'=>'root',
'pwd'=>'root',
'db'=>'shop',
];
$productid=intval($_POST['productid']);
$num=intval($_POST['num']);
$cart=newCart($user);
//添加到购物车
$cart->add_cart($productid,$num);
//删除指定的商品
$cart->remove_cart($productid);
//清空
$cart->clear_cart();
?>
更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP+MySQL购物车开发专题》、《php面向对象程序设计入门教程》、《PHP数学运算技巧总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《PHP数据结构与算法教程》、《php程序设计算法总结》、《php正则表达式用法总结》、及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短