从数组中将多行插入数据库

时间:2011-01-16 18:35:24

标签: php mysql database arrays foreach

我需要一些帮助,将不同数组中的多行插入我的数据库。

我正在制作座位计划的数据库,每个座位区有5排(A-E),每排有15个座位。

我的数据库行是seat_id,seat_block,seat_row,seat_number,因此我需要为每个seat_row添加15个seat_numbers,为每个seat_block添加5个seat_rows。

我用一些foreach循环模拟了它,但是需要一些帮助将它变成一个(希望是单一的)SQL语句。

$blocks = array("A","B","C","D");
$seat_rows = array("A","B","C","D","E");
$seat_nums = array("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15");

foreach($blocks as $block){

    echo "<br><br>";
    echo "Block: " . $block . " - ";

    foreach($seat_rows as $rows){

        echo "Row: " . $rows . ", ";

        foreach($seat_nums as $seats){
            echo "seat:" . $seats . " ";
        }

    }
}

也许有更好的方法来做而不是使用数组? 我只想避免编写超过100行的SQL语句;)

(我也使用codeigniter,如果有人知道CI特定的做法,但我不会太烦恼)

2 个答案:

答案 0 :(得分:2)

<?php

    $blocks = array("A","B","C","D");
    $seat_rows = array("A","B","C","D","E");
    $seat_nums = array("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15");

    foreach($blocks as $block){
        foreach($seat_rows as $rows){
            foreach($seat_nums as $seats){
                $querys[] = "('" . $block "','" . $rows . "', '" . $seats . "' )";
            }
        }
    }

    $query_inserts = join ( ", ", $querys );

    $query = "
        INSERT INTO
            table
        ( block, rows, seats )
        VALUES
            " . $query_inserts . "
        ";

    mysql_query ($query);



?>

答案 1 :(得分:1)

一种解决方案是使用预先准备好的陈述:

$pdo = new PDO('mysql:dbname=mydb', 'myuser', 'mypass');

$stmt = $pdo->prepare('INSERT INTO seats 
                          (seat_id, seat_block, seat_row, seat_number)
                          VALUES (?,?,?,?);
                     ');

foreach (...) {
   $stmt->execute(array($seat_id, $seat_block, $seat_row, $seat_number));
}