PHP生成动态PDO插入 [英] PHP generate dynamic PDO insert

查看:41
本文介绍了PHP生成动态PDO插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码应将数组中的每个键值对插入表中的数学列值中.该脚本未返回任何错误,但插入的行仅包含数组中的最后一个值

The following code should insert each key-value pair in an array into a mathing column-value in a table. The script returns no errors but the the inserted row contains only the last value in the array

例如

array('one'=>1,'two'=>2,'three'=>3);

将行成功插入到具有第一,第二和第三列的表中,但总共插入值3.

insert the row successfully in a table with columns one, two and three but insert the value 3 in all.

    $columns = array();
    $bind = '';
    foreach($array as $key => $value){

        $columns[] = $key;

    }

    $columnString = implode($columns,',');
    $valueString = implode($columns,',:');
    $valueString = ':' . $valueString;

    $core = core::getInstance();
    $STH = $core->dbh->prepare("INSERT INTO table (" . $columnString . ") VALUES 
    (" . $valueString . ")");

    foreach($array as $key => $value){

        $STH->bindParam(':' . $key,$value);
    }

推荐答案

忘了bindParam,只需使用execute并将值$array传递给它即可:

Forget about bindParam, just use execute and pass it the values of $array:

$STH->execute($array);

或者,您可以完全擦除命名的参数,以简化您的代码:

Alternatively, you could scratch the named parameters altogether to simplify your code a little:

$columnString = implode(',', array_keys($array));
$valueString = implode(',', array_fill(0, count($array), '?'));

$STH = $core->dbh->prepare("INSERT INTO table ({$columnString}) VALUES ({$valueString})");
$STH->execute(array_values($array));

这篇关于PHP生成动态PDO插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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