tags:

views:

68

answers:

3

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  A: 

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.

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

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

MatTheCat
A: 

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
}
A.