phploopsmysqlisql-insertsubmission

Create an HTML form with repeatable fields and insert form submission as multiple rows into database


I can add multiple rows into my database using the below

$sql = 'INSERT INTO 'tablename' ('column1', 'column2') VALUES
    ('data1', 'data2'),
    ('data3', 'data4'),
    ('data5', 'data6'),
    ('data7', 'data8');
';

But I can't work out how to create a form that will allow me to add multiple rows into the database.

In the past when I just want to add in one row at a time I have been able to do something like this in my form.

<input type="text" name="name" value="">

and the below in my PHP

$_POST['name']

but this doesn't work when you want to insert multiple rows. Can someone please point me in the right direction here?


Solution

  • You can use php arrays, so you do

    <input type="text" name="name[]" value="">
    

    note the square brackets added after name. You can have multiple instances of this in your form and then refer to it in the php as:

    $_POST['name'][$i]
    

    where $i is a variable indexing the value in the array.