php - 1类中的多个sql语句
问题描述
我是 OOP php 的新手,我正在尝试创建一个简单的添加到购物车功能,当用户将产品添加到购物车时,产品 ID 将被插入到购物车表中,我想从帖子中获取产品价格根据购物车表中的产品 ID 表添加到购物车价格列,产品 ID 已插入购物车表但我无法获取价格。
<?php
class Post{
private $db;
public function __construct(){
$this->db = new Database;
}
public function getprice($id){
$this->db->query('SELECT * FROM posts WHERE id = :id');
$this->db->bind(':pirce', $price);
$results = $this->db->resultSet();
return $results;
}
//add to cart
public function addcart($data){
$price = $this->getprice($id);
$this->db->query('INSERT INTO cart (p_id, size ,price) VALUE (:id, :qty, $price)');
//bind values
$this->db->bind(':id', $data['id']);
$this->db->bind(':qty', $data['qty']);
$this->db->bind($price);
// Execute
if($this->db->execute()){
return true;
} else {
return false;
}
}
}
解决方案
<?php
class Post{
private $db;
public function __construct(){
$this->db = new Database;
}
public function getprice($id){
$this->db->query('SELECT * FROM posts WHERE id = :id');
$this->db->bind(':id', $id);
$results = $this->db->resultSet();
return $results;
}
//add to cart
public function addcart($data){
$post = $this->getprice($data['id']);
$this->db->query('INSERT INTO cart (p_id, size ,price) VALUE (:id, :qty, :price)');
//bind values
$this->db->bind(':id', $data['id']);
$this->db->bind(':qty', $data['qty']);
$this->db->bind(':price', $post->price);
// Execute
if($this->db->execute()){
return true;
} else {
return false;
}
}
}
推荐阅读
- c# - 登录验证成功后无法显示第二个表单
- python - 使用 PyMySQL 将数据插入 MySQL 中的表
- java - jvm dup指令的用例
- haskell - 表达式中的模式匹配运算符/构造函数
- dart - 点击 ListView Flutter 布局中的整行
- java - 澄清堆栈是如何通过 Java 中的对象实现的?
- git - 尝试从 Katalon Studio 中的 Git 主分支提取时出现 Git 错误
- visual-studio-code - 用于设置工作目录的 API 或上下文菜单
- java - Windows 7中的JPA Eclipselink查询解析问题
- typescript - VS Code 和 Typescript 观察:文件正在重新编译而不保存