且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将多维php数组插入mysql数据库

更新时间:2022-12-11 20:49:40

以下代码将起作用,但是它假定所有嵌套数组的长度都相同,换句话说,每个嵌套数组都包含所有属性的值在第一个嵌套数组中定义.

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)

有关演示,请参见 http://codepad.org/7SG7lHaH ,但请注意,我删除了通话到codepad.org上的mysql_real_escape_string(),因为它们不允许使用该函数.在您自己的代码中,您应该使用它.

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.