PDO获取到现有对象

时间:2013-12-28 22:42:33

标签: php pdo

我正在尝试使用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.

我搜索了很长时间,没有结果。我见过的所有解决方案都具有类外的功能,或者它们返回一个新对象,而不是当前的对象。

2 个答案:

答案 0 :(得分:1)

在模型/值对象中使用PDO来填充对象的属性是可怕的设计决策。我不是说要敲你的代码,而是鼓励你使用不同的技术。您在可维护性方面所避免的痛苦将值得选择新设计。解决后我有一个建议。

<强>解

此问题之前已在此处理过:“PDO's FETCH_INTO $this class does not working”。使用该技术应该解决您的问题。

<强> SUGGESTION

我的建议是完全走另一条路。考虑创建一个看起来像这样的凭证DAO:

class VoucherDao
{
    private $db;

    public function __construct(\PDO $db)
    {
        $this->db = $db;
    }

    public function findVoucher($voucher_code)
    {
        $stmt = $this->db->prepare('select * from cart_voucher_table where voucher_code = :voucher_code');
        $stmt->bindValue(':voucher_code', $voucher_code);
        $stmt->setFetchMode(\PDO::FETCH_CLASS, 'Voucher');
        $stmt->execute();

        return $stmt->fetch();
    }
}

您可以使用DAO创建已填充数据的凭证,而不是创建新的凭证然后加载它。

$dao = new VoucherDao($conn);
$voucher = $dao->findVoucher(12345);

当然,由于我没有完整的优惠券代码,我无法测试。如果我没记错的话,您需要在您的凭证类中创建设置器以允许PDO::FETCH_CLASS正常工作。如果你试试我的建议,可以使用和不使用。

答案 1 :(得分:0)

“input_parameters中的键必须与SQL中声明的键匹配。在PHP 5.2.0之前,这是默认忽略的。”

来自:http://www.php.net/manual/de/pdostatement.execute.php

在你的MySQL中,在准备语句时,你有命名参数“:voucher_code”,但是数组中用于执行的键是“transaction_id” - 所以这可能是你的问题我猜,因为你写了一个关于获取的评论有关参数的错误消息。

另外,我在代码中的任何地方都看不到$ stmt-&gt; fetch()?

相关问题