大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
这篇文章主要讲解了“php+pdo实现的购物车类代码分享”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“php+pdo实现的购物车类代码分享”吧!
我们提供的服务有:成都做网站、网站制作、成都外贸网站建设、微信公众号开发、网站优化、网站认证、永川ssl等。为超过千家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的永川网站制作公司
本文实例讲述了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+pdo实现的购物车类代码分享”的内容了,经过本文的学习后,相信大家对php+pdo实现的购物车类代码分享这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联,小编将为大家推送更多相关知识点的文章,欢迎关注!