Inserting Multiple Rows with PHP & MySQL

2019-06-09 15:20发布

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.

<?php

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">
<table>
  <tr>
    <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 

  </tr>
</table>
<input type="submit" name="submit" value="Submit">
</form>

    <?php
}
?>

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.

标签: php sql insert
2条回答
迷人小祖宗
2楼-- · 2019-06-09 16:00

First thing you want to avoid is use same set of names. You may want to name them rowNcolM and then extract them where you check post variables.

查看更多
戒情不戒烟
3楼-- · 2019-06-09 16:10

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
{
    echo($_POST["column1"][$i]);
    echo($_POST["column2"][$i]);
    echo($_POST["column3"][$i]);
}

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

INSERT INTO
    tbl_name (column1, column2, column3)
VALUES
    (1,2,3),
    (4,5,6),
    (7,8,9);

Now you should be set to build your SQL query.

查看更多
登录 后发表回答