基于数组键作为列名的PDO插入 [英] PDO insert based on array keys as column names

查看:79
本文介绍了基于数组键作为列名的PDO插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PDO插入语句,该语句从表单提交中更新数据库表.有很多领域.我特意使用了与html输入名称相同的列名称.有没有更干净的方式布置此代码?目前,我有30个以上的$_POST变量,并且希望通过某种形式的循环使用更简洁的解决方案.

I have a PDO insert statement that updates a database table from a form submission. There are many fields. I have purposely used the same column names as the html input names. Is there a cleaner way of laying out this code? Currently I have 30+ $_POST variables and would prefer a cleaner looking solution via a loop of some kind.

这是我目前的实现方式,例如,为了方便起见,我仅包括了几个字段.

This is my current implementation, I've only included a few fields for example's sake.

$stmt = $dbh->prepare("INSERT INTO myTable SET Col1 = ?, ColABC = ?, Col123 = ?, ColFoo = ?, ColDEF = ?");
$stmt->execute(
    array($_POST['Col1'], $_POST['ColABC'], $_POST['Col123'], $_POST['ColFoo'], $_POST['ColDEF'])
);

推荐答案

尝试类似以下操作

$postarr = array('Col1', 'ColABC', 'Col123', 'ColFoo', 'ColDEF'); //<---- defined all the form elements you like to get from post
$sql = ''; $param = array();
foreach($postarr as $k){
    $sql .= $k.'=:'.$k.','; // setting up placeholders for columns we are goign to update or get value from $_POST data
    $param[$k] = $_POST[$k]; // setting up param array argument for execute() function
}
$sql = substr($sql,0,-1); // <--- remove last ,
$stmt = $dbh->prepare("INSERT INTO myTable SET " . $sql);
$stmt->execute($param);

这篇关于基于数组键作为列名的PDO插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆