简体   繁体   中英

insert multiple rows into database from arrays

i need some help with inserting multiple rows from different arrays into my database.

I am making the database for a seating plan, for each seating block there is 5 rows (AE) with each row having 15 seats.

my DB rows are seat_id, seat_block, seat_row, seat_number, therefore i need to add 15 seat_numbers for each seat_row and 5 seat_rows for each seat_block.

I mocked it up with some foreach loops but need some help turning it into an (hopefully single) SQL statement.

$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 . " ";
        }

    }
}

Maybe there's a better way of doing it instead of using arrays? i just want to avoid writing an SQL statement that is over 100 lines long ;)

(im using codeigniter too if anyone knows of a CI specific way of doing it but im not too bothered about that)

try

<?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);



?>

One solution is to use prepared statements:

$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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM