Inserting a multi-dimensional php array into a mysql database

前端 未结 8 2020
耶瑟儿~
耶瑟儿~ 2020-12-11 03:36

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

$array = array(
    array(\'name\', \'age\', \'gender\'),
    array(\'Ian\', 24, \'male\'),
    a         


        
8条回答
  •  醉酒成梦
    2020-12-11 03:59

    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 http://codepad.org/7SG7lHaH, but note that I removed the call to mysql_real_escape_string() on codepad.org, because they do not allow the function. In your own code you should use it.

提交回复
热议问题