完整示例php+pdo实现的购物车类

coldplay.xixi
发布: 2023-04-09 10:38:02
转载
2703 人浏览过

完整示例php+pdo实现的购物车类

本文实例讲述了php+pdo实现的购物车类。分享给大家供大家参考,具体如下:

pdo = new PDO("mysql:host=$host;dbname=$db", "$user", "$pwd", array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); $this->pdo->query("set names utf8"); } catch (PDOException $e) { echo $e->getMessage(); } } //添加商品到购物车 public function add_cart($productid, $num) { $sql = "select price from shop_product where id=?"; $stmt = $this->pdo->prepare($sql); $stmt->execute(array($productid)); $data = $stmt->fetch(PDO::FETCH_ASSOC); $price = $data['price']; $createtime = time(); $sql = "select * from shop_cart where productid=? and userid=?"; $stmt = $this->pdo->prepare($sql); $stmt->execute(array($productid, $_SESSION['user_id'])); $data = $stmt->fetch(PDO::FETCH_ASSOC); if ($data) { $sql = "update shop_cart set num=num+? where userid=? and productid=?"; $params = array($num, $_SESSION['user_id'], $productid); } else { $sql = "insert into shop_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'); } //修改购买数量 public function change_num($productid, $num) { $sql = "update shop_cart set num=? where userid=? and productid=?"; $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'); } //清空购物车 public function clear_cart() { $sql = "delete from shop_cart where userid=?"; $stmt = $this->pdo->prepare($sql); $this->pdo->execute(array($this->user_id)); $rows = $stmt->rowCount(); return $rows ? show(1, 'ok', $rows) : show(0, 'fail'); } //从购物车中删除商品 public function remove_cart($productid) { $sql = "delete from shop_cart where productid=? and userid=?"; $stmt = $this->pdo->prepare($sql); $stmt->execute(array($productid, $_SESSION['user_id'])); $rows = $stmt->rowCount(); return $rows ? show(1, 'ok', $rows) : show(0, 'fail'); } } //处理数据 function show($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 = new Cart($user); //添加到购物车 $cart->add_cart($productid, $num); //删除指定的商品 $cart->remove_cart($productid); //清空 $cart->clear_cart(); ?>
登录后复制

相关学习推荐:PHP编程从入门到精通

以上是完整示例php+pdo实现的购物车类的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:jb51.net
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!