如何在数据库表中插入多行?

时间:2016-09-30 05:00:11

标签: foreach

我想使用foreach在单个表中插入多行。

<pre  class='code'>Array
(
    [instructor_id] => 76
    [vehicle_id] => 2
    [arr_bookings] => Array
    (
        [0] => Array
            (
                [0] => 07-10-2016
                [1] => 1:10 PM
                [2] => 2:02 PM
                [3] => s
                [4] => s
            )

        [1] => Array
            (
                [0] => 07-10-2016
                [1] => 1:15 PM
                [2] => 2:01 PM
                [3] => a
                [4] => a
            )

    )

)

我的结果是print_r($ result)。我如何使用foreach插入?关于这一点的任何想法。

1 个答案:

答案 0 :(得分:0)

你会做类似的事情。

$sql = "INSERT INTO table_name (column_1, column_2) VALUES";

然后循环遍历你的数组,

$last_key = end(array_keys($array));

foreach ( $array as $key => $value ) {
    // Don't forget to protect against SQL injection.
    $sql .= "('$value[0]', '$value[1]')";

    if ( $last_key === $key ) {
        $sql .= ",";
    }
}

之后你应该有一个类似INSERT INTO table_name (column_1, column_2) VALUES ('Some Value', 'Another Value'), ('foo', 'bar')的SQL语句。