【发布时间】:2013-12-29 07:43:56
【问题描述】:
我正在尝试使用 PDO 将数据从数据库中提取到当前对象中。代码:
class Voucher {
//Database and object have EXACTLY the same fields/properties/columns
protected $voucher_id;
protected $voucher_code;
protected $voucher_value;
protected $voucher_product_type;
protected $voucher_status;
// still in the class declaration
public function load_voucher($voucher_code){
global $conn; //load database connection info
$stmt = $conn->prepare('select * from cart_voucher_table where voucher_code = :voucher_code');
$stmt->execute(array('transaction_id' => $this_transaction_id));
I HAVE NO IDEA, NO PDO statement works
// Current object (which existed but was empty) now contains values from first row of returned data from db
}
}
//用法
$this_voucher = new voucher(); //creates new voucher object
$this_voucher->load_voucher($voucher_code); //loads data from database into the current voucher object.
我找了好久,没有结果。我见过的所有解决方案要么具有类之外的函数,要么返回一个新对象,而不是当前对象。
【问题讨论】:
-
当您为
voucher_code准备语句时执行时,您正在映射transaction_id。此外,$this_transaction_id未定义,但我确定您的意思是使用$this->transaction_id -
你遇到了什么错误?
-
是的。解决了这个问题。它仍然不起作用。它在 $stmt->setFetchMode(PDO:FETCH_CLASS, 'Voucher'); 上失败这是在实际执行查询之前。错误是:未捕获的异常 'PDOException' 带有消息 'SQLSTATE[HY093]:无效的参数号:未定义参数
-
我已经尝试了设置获取模式和执行我能想到的语句的所有变体。我相信我需要一行来设置 PDO 模式以获取当前对象,但我不知道如何设置它。
-
在执行前尝试使用
bindValue()。