【问题标题】:PDO prepared statement with dynamic variables [duplicate]具有动态变量的 PDO 准备语句 [重复]
【发布时间】:2017-06-11 16:03:33
【问题描述】:

我想创建一个可以使用 PDO 准备语句将数据插入数据库的函数

public function test() {
  $this->insert([
    'first_name' => $_POST['first_name'],
    'last_name' => $_POST['last_name'],
    'email' => $_POST['email']
  ]);
}


public function insert(array $data) {

  $fields = '';
  $bindValues = '';
  $values = [];

  foreach($data as $k => $v) {
    $fields .= $k . ', ';
    $bindValues .= ':' . $k . ', ';
    $values[$k] = $v; 
  }

  $fields = rtrim($fields, ', ');
  $bindValues = rtrim($bindValues, ', ');

  $insert = $this->db->prepare("
    INSERT INTO
      :table
    (:fields)
    VALUES 
      (:values)
  ");

  $insert->execute([
    'table' => $this->table,
    $values
  ]);  
}

dumped variables: 
1. $fields
2. $bindValues 
3. $values


'first_name, last_name, email' (length=28)
':first_name, :last_name, :email' (length=31)
array (size=3)
  'first_name' => string 'Nikola' (length=6)
  'last_name' => string 'Misic' (length=5)
  'email' => string 'mail@mail.com' (length=13)

我得到一个错误

在布尔值上调用成员函数 execute()

SQL 有问题,我不知道如何调试它。

【问题讨论】:

  • 您不能绑定表或列。绑定也应该有 1 个值。

标签: php pdo prepared-statement


【解决方案1】:

您需要使用类似...的方式构建 SQL

$insert = $this->db->prepare("
    INSERT INTO
      {$this->table}
    ($fields)
    VALUES 
      ($bindValues)
  ");

【讨论】:

  • 是的,我已经做到了,但我认为我可以使用准备功能做到这一点。我不知道您不能绑定表或列。谢谢。
  • 你应该非常小心让用户输入到查询中 - 使用准备好的语句的全部意义都消失了
猜你喜欢
  • 1970-01-01
  • 2011-11-28
  • 2013-10-26
  • 1970-01-01
  • 1970-01-01
  • 2014-04-19
  • 1970-01-01
  • 2013-02-22
相关资源
最近更新 更多