Given the following array;
[0] => array(
col1 => val1,
col2 => val2,
col3 => val3
),
[2] => array(
col1 => val1,
col2 => val2,
col3 => val3
),
[3] => array(
col1 => val1,
col2 => val2,
col3 => val3
)
And a database table with the same column names col1
, col2
and col3
What's the most efficient way to insert this into a database?
I currently have something like this;
$i = 0;
$db_columns = '';
$column_values = array();
foreach ($rows as $k => $row)
{
$columns = array();
$fields = array();
foreach ($row as $a => $b)
{
$column_values[$a.$i] = $b;
$columns[] = ':'.$a.$i;
$fields[] = $a;
}
// build up sql values
$db_columns .= ($db_columns ? ', ' : '').'('.implode(', ', $columns).')';
$i++;
}
// perform insert
$sql = "INSERT INTO table (".implode(', ', $fields).")
VALUES $db_columns";
$query = $db->prepare($sql);
$status = $query->execute($column_values);
Which will build the query string like so;
INSERT INTO table (col1, col2, col3)
VALUES (:col10, :col20, :col30), (:col11, :col21, :col31), (:col12, :col22, :col32)
With an array to match the bound variables :col10
, :col20
, :col30
, :col11
etc...
So all well and good. It does what I want and works, but the code to me seems overly complicated considering the input array keys match the table. There must be a cleaner way to do this.