cam
cam

Reputation: 1

Loop through form input array

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

Upvotes: 0

Views: 5772

Answers (3)

VoteyDisciple
VoteyDisciple

Reputation: 37813

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.

Upvotes: 1

NOtherDev
NOtherDev

Reputation: 9682

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
}

Upvotes: 1

MatTheCat
MatTheCat

Reputation: 18761

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

Upvotes: 0

Related Questions