7

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

例如

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

5 回答 5

10

忘记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));
于 2012-08-18T15:55:55.077 回答
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);
}
于 2012-08-18T15:55:38.900 回答
0
foreach($array as $key => $value){
    $STH->bindParam(':' . $key,$array[$key]);
}

试试看

于 2012-08-18T15:42:11.833 回答
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);

于 2021-02-26T16:17:12.977 回答
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";
}
于 2017-05-30T09:34:07.860 回答