-1

我正在为 PHP PDO 编写一个类,以便我可以缩短准备和执行方法。

不必每次都编写准备和绑定:

$db = new PDO('sqlite:db.sdb');
$prep = $db->prepare("INSERT INTO animals (animal_type, animal_name) VALUES (:animal_type, :animal_name)");
$data_to_set = array(':animal_type' => 'Cow', ':animal_name' => 'Carolina');
$prep->execute($data_to_set);

在这种情况下, animal_type 和 animal_name 会重复,所以我创建了一个类来消除它:

class QuickPDO{

    public $fields, $values, $args;

    public function __construct($args){

        foreach ($args as $key => $value) {
            $this->fields .= substr($key, 1).', ';
            $this->values .= $key.", ";
        }
        $this->values= substr($this->values, 0, -2);
        $this->fields = substr($this->fields, 0, -2);
        $this->args = $args;

    }

    public function insert($table){
        $returning_query = "INSERT INTO $table ($this->fields) VALUES ($this->values)";
        return $returning_query;
    }

}

所以这变得更容易并变成:

$myPDO = new QuickPDO([':animal_type' => 'Cow', ':animal_name' => 'Carolina']);
$prep = $db->prepare($myPDO->insert('animals'));
$prep->execute($myPDO->args);

到这里,没问题。但是这样我只能为每个QuickPDO Object做一个prepare,不是很方便,所以我想把__construct改成一个函数“set”:

public function set($args){

    foreach ($args as $key => $value) {
        $this->fields .= substr($key, 1).', ';
        $this->values .= $key.", ";
    }
    $this->values= substr($this->values, 0, -2);
    $this->fields = substr($this->fields, 0, -2);
    $this->args = $args;

}

并这样称呼它:

$myPDO = new QuickPDO();
$myPDO->set([':animal_type' => 'Cow', ':animal_name' => 'Carolina']);   
$prep = $db->prepare($myPDO->insert('animals'));
$prep->execute($myPDO->args);

当我尝试对 $myPDO 执行新的 set() 时,问题就出现了。我做错了什么,但我无法弄清楚它是什么。

4

1 回答 1

0

好的,解决了

$myPDO->set([':animal_type' => 'Like', ':animal_name' => 'This']);
$prep = $db->prepare($myPDO->insert('animals'));
$prep->execute($myPDO->args);
$myPDO->set([':animal_type' => 'Works', ':animal_name' => 'Fine']);
$prep->execute($myPDO->args);

顺序很重要...

于 2013-07-07T22:18:33.990 回答