I've been playing around for few hours and trying to sort this out but looks like a hard nut to crack.
I'm able to do a single array insertion
$person = array('name' => 'Wendy', 'age' => '32');
but if I want multiple like this:
$person = array(array('name'=>'Dan', 'age'=>'30'), array('name' => 'John', 'age' => '25'), array('name' => 'Wendy', 'age' => '32'));
It's not working? Any help would be appreciated.
For multiple insertion:
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();
}
}
For Single Insertion
$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);
And the error:
Error: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens