0

I have a functional HTML form and I am inserting it's contents to SQL database via PHP. I need to find a way to be able to insert multiple rows on just one click (customers will dynamically add more form fields as they wish).

This is the HTML field (part of the form):

<label for="code">Súťažný kód</label>
<input type="text" name="code" id="code">

I am then passing the field value to external .php file using jQuery:

jQuery.ajax({
  url:"insert.php",
  method:"POST",
  data:form_data,
  success:function(data) {
    console.log(data);
  }
});

In the insert.php I am connecting to my MySQL database, and I am getting the form value like this:

$code = $_REQUEST['code'];

Than, I am able to run necessary SQL queries to insert the row, with the all necessary values (including the 'code').

This form will be used as a submit form for a contest. Next to the 'code' form field there will be a PLUS icon (or something like that), and by clicking that icon, another field for the code will appear. The user will be able to add up to 20 codes, to 20 different fields.

My question is, how can I pass all the forms (or all the codes) to the .php file, and insert them into my MySQL database as separate rows?

Example:

User sends a form with 3 codes inserted. The resulting form would look like this:

[firstName]
[lastName]
[code]
[code]
[code]

After sending the form, these three rows should be added to the database:

#  | firstName | lastName | code
----------------------------------
1  | John      | Doe      | 12345
2  | John      | Doe      | ABCDE
3  | John      | Doe      | 55555

1 Answer 1

2

Change field to be an array, like:

<input type="text" name="code[]" id="code1">
<input type="text" name="code[]" id="code2">

then you can access it in PHP like:

foreach ($_REQUEST['code'] as $key => $val) {
   sql_insert_function($_REQUEST['firstName'], $_REQUEST['lastName'], $val);
}

As a general advice, remember to validate and escape all the data you're going to insert in a database.

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

3 Comments

this is the right approach from the point of view of the form. But what is mysql_insert()?
Just imagine it's pseudocode for whatever function you use to insert sql. Will clarify that in the name.
This is very helpful, I had no clue a field can be an array. Yes, I am using prepared statements and some other security approachs.

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.