0

I have a dynamic output form where the text input fields have the same name. I need to loop through the text inputs and insert multiple rows into the database for each text field input.

$sql="INSERT INTO orderitems (orderNum,productNum,quant)
      VALUES
     ('$num1','$_POST[pNum]','$_POST[quant]')";


<input type="text"  name="pNum" value="<?php echo $t1; ?>"> //may have several with same name
1

3 Answers 3

1

If you want to submit your form with multiple inputs with the same name, you should add [] to the name. Then you can use it on PHP-side as every array (i.e. looping with foreach)

<input type="text" name="pNum[]" value="<?php echo addslashes($t1); ?>"> (by the way, remember always about quoting)

and on PHP side:

foreach($_POST['pNum'] as $value)
{
   // remember about quoting here, too
}
Sign up to request clarification or add additional context in comments.

Comments

1

Soooo.... loop through them and insert multiple rows?

for ($i = 0; $i < count($_POST['pNum']); $i++) {
    $sql = 'INSERT INTO orderitems (orderNum, productNum, quant) VALUES ('
      . "'" . mysql_real_escape_string($num1) . "', "
      . "'" . mysql_real_escape_string($_POST['pNum'][$i]) . "', "
      . "'" . mysql_real_escape_string($_POST['quant'][$i]) . "'"
      . ')';
}

Note the use of mysql_real_escape_string. Never, NEVER, NEVER inject values from $_POST or $_GET or $_COOKIE or any other value your user has supplied directly into a SQL statement. Besides the potential to break if the value contains a ', this can also be used maliciously to inject SQL that alters (or erases) your database.

3 Comments

Request in a loop is bad, you can insert many rows with only one INSERT request.
It's not that bad. For small sets of data, the added complexity of trying to generate a single INSERT isn't worth it.
Thank you for your reply, for some reason this is only selecting the last input field and inserting it twice. Any ideas?
0

You can insert many rows with an INSERT request, you have just to create it with PHP http://dev.mysql.com/doc/refman/5.0/en/insert.html

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.