php-pdo多数组插入


php pdo multi array insert

我已经玩了几个小时,试图解决这个问题,但看起来很难解决。

我可以进行单个阵列插入

$person = array('name' => 'Wendy', 'age' => '32');

但如果我想要这样的多个:

$person = array(array('name'=>'Dan', 'age'=>'30'), array('name' => 'John', 'age' => '25'), array('name' => 'Wendy', 'age' => '32'));

它不起作用?如有任何帮助,我们将不胜感激。

对于多次插入:

public function insertPdo($table, $data){
    try{
        if (!is_array($data) || !count($data)) return false;
        $bind = ':' . implode(', :', array_keys($data));      
        $sql = 'INSERT INTO ' . $table . ' (' . implode(', ',array_keys($data)) . ') ' . 'values (' . $bind . ')';
        $sth = $this->__dbh->prepare($sql);
        $result = $sth->execute($data);
    }
    catch(PDOException $e){
        echo $e->getMessage();
    }
}

对于单次插入

$person = array('name'=>'Dan', 'age'=>'30');
$db->insertPdo('test_pdo',$person);
// For Multi Insertion, I'm trying to use this in above function
foreach ($data as $row) {
    $result = $sth->execute($row);
};
$person = array(array('name'=>'Dan', 'age'=>'30'), array('name' => 'John', 'age' => '25'), array('name' => 'Wendy', 'age' => '32'));
$db->insertPdo('test_pdo',$person);

错误:

错误:SQLSTATE[HY093]:参数编号无效:绑定变量的数量与令牌的数量不匹配

为了利用MySQL中多个插入的插入速度(http://dev.mysql.com/doc/refman/5.0/en/insert-speed.html),您可以使用一个准备好的语句来构建更大的查询。这确实增加了迭代方法的复杂性,因此可能只适用于高需求系统或较大的数据集。

如果你有你上面建议的数据:

$person = array(array('name'=>'Dan', 'age'=>'30'), array('name' =>
'John', 'age' => '25'), array('name' => 'Wendy', 'age' => '32'));

我们希望生成一个查询,看起来像这样:

insert into table (name, age) values (?,?), (?,?), (?,?);

要把这一切结合起来,你会想要一些与此完全不同的东西:

$pdo->beginTransaction() // also helps speed up your inserts
$insert_values = array();
foreach($person as $p){
   $question_marks[] = '(?,?)';
   $insert_values = array_merge($insert_values, array_values($p));
}
$sql = "INSERT INTO table_name (name, age) VALUES " . implode(',', $question_marks);
$stmt = $pdo->prepare ($sql);
try {
    $stmt->execute($insert_values);
} catch (PDOException $e){
    // Do something smart about it...
}
$pdo->commit();

您不能自动执行此操作。相反,您必须手动迭代并执行每条记录:

for ($person as $row) {
    $sth->execute($row);
}