0

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 (A-E) 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)

1
  • Have you thought of using ENUMs, one for block, row, and num? Commented Jan 16, 2011 at 18:38

2 Answers 2

3

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



?>
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.