PHP PDO动态查询构建器类

时间:2018-07-10 09:46:33

标签: php oop pdo

我正在编写一个类以生成动态SQL插入查询。如果我还考虑作为自动增量值的id,那么我已经创建了一个包含7列的测试表,否则该值仅为6。我试图测试我编写的插入函数是否有效,但是控制台向我记录了一个与有界变量的数量有关的错误:PHP Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens。 通常,我习惯于编写查询,这是我第一次收到此错误。是否可能需要在查询中也包含id列字段? 这是代码:

测试页

<?php
$dataManager = new DataManager($db);

$table = 'hats_info';
$data = array('test0','test1','test2','test3','test4','test5');
$columns = array('materialA','materialB','materialC','materialD','accessories','hat_image');
$holders = array('?','?','?','?','?','?');

echo $dataManager->insert($data, $table, $columns, $holders);

?> 

类方法代码

<?php 

public function insert($table, array $data, array $columns , array $holders){

    $columns = implode(', ', array_values($columns));
    $holders = implode(', ', array_values($holders));
    $values = implode(', ', array_values($data));

    $stmt = $this->db->prepare("INSERT INTO $table ($columns) VALUES ($holders)");
    return $stmt->execute(array($values));
}

?>

1 个答案:

答案 0 :(得分:1)

我已经通过以下方式完成了这样的功能:

$table = 'hats_info';

$data = [
  'materialA' => 'test0',
  'materialB' => 'test1',
  'materialC' => 'test2',
  'materialD' => 'test3',
  'accessories' => 'test4',
  'hat_image' => 'test5'
];

echo $dataManager->insert($table, $data);

public function insert($table, array $data) {
    $columns_delimited = implode(', ' array_map(
        function ($column) { return "`$column`"; },
        array_keys($data)
    ));
    $placeholders = implode(', ', array_fill(1, count($data), '?'));
    $sql = "INSERT INTO `$table` ($columns_delimited) VALUES ($placeholders)"
    $stmt = $this->db->prepare($sql);
    return $stmt->execute(array_values($data));
}