我愚蠢地用 mysqli 构建了我的 Web 应用程序。现在,我正在尝试将我的数据抽象层转换为 pdo,但由于某种原因,插入查询给我带来了麻烦。我的快捷插入函数是从控制器调用的,我希望将其保持为名称格式,并以表名和列/值数组作为参数。
我评论了我认为问题出在哪里。请帮忙。
function insert($table, array $columns_values) {
// connect to db
$dbh = $this->db_connect();
$i = 0;
$columns = array();
$values = array();
$params = array();
foreach($columns_values as $column => $value) {
$i++;
$param = array($i => $value);
array_push($params, $param);
array_push($columns, $column);
array_push($values, '?');
}
// turn arrays into comma separated list
$columns = implode(",", $columns);
$values = implode(",", $values);
$stmt = $dbh->prepare("INSERT INTO $table ($columns) VALUES ($values)");
foreach ($params as $param_stmt) {
// i think this is where the problem is
foreach ($param_stmt as $placeholder => $value) {
$stmt->bindParam($placeholder, $value);
}
}
$stmt->execute();
return $stmt;
} // end insert()