PHP生成动态PDO插入

时间:2012-08-18 15:33:03

标签: php mysql pdo

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

E.g。

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

在包含第一,第二和第三列的表中成功插入行,但在所有值中插入值3。

    $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);
    }

5 个答案:

答案 0 :(得分:6)

忘记bindParam,只需使用execute并传递$array的值:

$STH->execute($array);

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

$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));

答案 1 :(得分:2)

可能是这样的:

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

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

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

foreach($columns as $key => $value){
    $STH->bindValue(':' . $key, $value);
}

答案 2 :(得分:0)

foreach($array as $key => $value){
    $STH->bindParam(':' . $key,$array[$key]);
}

试试

答案 3 :(得分:0)

$conn = new PDO('mysql:host=' . $HOST . ';dbname=' . $DATABASE, $USERNAME, $PASSWORD);
$conn->exec("set names utf8");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);

$ins_query = 'INSERT INTO `' . $table_name . '` ';

$columns = array();
$columns_bindings = array();
foreach ($dataArray as $column_name => $data) {
    $columns[] = $column_name;
    $columns_bindings[] = ':' . $column_name;
}

$ins_query = $ins_query . '(' . implode(', ', $columns) . ') VALUES (' . implode(', ', $columns_bindings) . ')';

$stmt = $conn->prepare($ins_query);

foreach ($dataArray as $column_name => $data) {
    $stmt->bindValue(":" . $column_name, $data);
}
if (!$stmt->execute()) {
    print_r($stmt->errorInfo());

} else {
    echo "Insertd";
}

答案 4 :(得分:0)

@netcoder 的回复也很好,如果想使用位置占位符实现您的目标。但是,您可以使用 sprintf 函数来准备使用命名占位符的动态 sql 查询。

$sql = sprintf("INSERT INTO table (%s) VALUES(%s)",
              implode(", ", array_keys($array)),
              ":" . implode(", :", array_keys($array)));

$pdo->prepare($sql);
$pdo->execute($array);