Inserting multiple lines with PHP & amp; MySQL


I'm building a website where people can place orders and this is the first time I've had to insert multiple rows at a time and I'm lost. I know that I need a FOR loop to perform this, but I'm lost as to how to construct the loop. I'm using PHP, MySQL (obviously) with jQuery. I'm using the jQuery to .append() a new select box into the form to allow the client to choose another item.

This is how I usually construct my code to allow users to insert into the database. My question is how and where would I insert a loop that way multiples rows can be submitted all at once without having to insert them one by one. Anything would be helpful, thank you.


if (isset($_POST['submit'])) {

    if (!$_POST['col1'] | !$_POST['col2'] | !$_POST['col3']) { die ("error"); }

    if (!get_magic_quotes_gpc()) {
        $_POST['col1'] = addslashes ($_POST['col1']);
        $_POST['col2'] = addslashes ($_POST['col2']);
        $_POST['col3'] = addslashes ($_POST['col3']);

    $insert = "insert into table (col1, col2, col3) values ('".$_POST['col1']."', '".$_POST['col2']."', '".$_POST['col3']."')";
    mysql_query ($insert);

} else {

<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
    <td><input type="text" name="col1"></td>
    <td><input type="text" name="col2"></td>
    <td><input type="text" name="col3"></td>

 //I'm using jQuery .append() to insert more text boxes with names (col1, col2, col3) here 

<input type="submit" name="submit" value="Submit">


My confusion is where to put the loop... I know it should be a FOR loop, but I could never get one to work. Thanks again for any help.

Be sure you name your inputs uniquely. But you can name every column like this (see here for example):

<input type="text" name="column1[]" />
<input type="text" name="column2[]" />
<input type="text" name="column3[]" />

That way you can access the columns via PHP using a for loop.

for($i = 0; $i < $n; $i++) // If you have $n rows

To insert multiple rows into your mySQL database use the following syntax (also: see here).

    tbl_name (column1, column2, column3)

Now you should be set to build your SQL query.