chentudou chentudou - 1 year ago 81
MySQL Question

Inserting a multi-dimensional php array into a mysql database

I have an array from a csv with a similar structure to this:

Array (
[0] => Array ( [0] => name [1] => age [2] => gender )
[1] => Array ( [0] => Ian [1] => 24 [2] => male )
[2] => Array ( [0] => Janice [1] => 21 [2] => female )

I would like to insert insert it into a mysql table where the items of the first array (name, age, gender) are the column titles and each subsequent array is a row in the table.

Could anyone advise as to the best way to do this as I have hit a wall and it has left me with a hurting head!

Answer Source

The following code will work, but it assumes that the length of all nested arrays is the same, in other words that each nested array contains values for all the attributes defined in the first nested array.

$array = array(
    array('name', 'age', 'gender' ),
    array('Ian', 24, 'male'),
    array('Janice', 21, 'female')

$fields = implode(', ', array_shift($array));

$values = array();
foreach ($array as $rowValues) {
    foreach ($rowValues as $key => $rowValue) {
         $rowValues[$key] = mysql_real_escape_string($rowValues[$key]);

    $values[] = "(" . implode(', ', $rowValues) . ")";

$query = "INSERT INTO table_name ($fields) VALUES (" . implode (', ', $values) . ")";

This solution will work with any number of attributes defined in the first nested array, as long as all other nested arrays have the same length. For the array above the output will be:

INSERT INTO table_name (name, age, gender) VALUES (Ian, 24, male), (Janice, 21, female)

For a demonstration see, but note that I removed the call to mysql_real_escape_string() on, because they do not allow the function. In your own code you should use it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download