本文实例讲述了PHP+pdo实现的购物车类。分享给大家供大家参考,具体如下:
<?PHPsession_start();class Cart{ public $pdo = null; public function __construct($config) { $host = $config['host']; $user = $config['user']; $db = $config['db']; $pwd = $config['pwd']; if (empty($_SESSION['user_ID'])) { return show(0, '请先登录'); } try { $this->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+pdo实现的购物车类所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)