我已经玩了几个小时并试图解决这个问题,但看起来很难破解。
我能够进行单个数组插入
$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]:无效的参数号:绑定变量的数量与标记的数量不匹配