fmdx
fmdx

Reputation: 39

How to insert into MYSQL row from multiple $_POST arrays

I have a form with an "add contact" section, where upon a click, it adds another row to the form with 3 more input boxes. (The segment of code on jfiddle: http://jsfiddle.net/fmdx/cYxYP/)

HTML

<form method="post" action="">
<div style="padding-left:40px;">
<div id="customcopies" style="padding-left:40px;">
1. Name: <input type="text" id="copiestoname_1" name="copiestoname[]" placeholder="Jane Doe Smith" required>, Institution: <input type="text" id="copiestoinst_1" name="copiestoinst[]" placeholder="Bank" required>, Method: <input type="text" id="copiestomethod_1" name="copiestomethod[]" placeholder="Email" required>
</div>
</div>
<input type="submit" name="submit_val" value="Submit" />
</form>

With this being the PHP/MYSQL for insertion:

if (isset($_POST['submit_val'])) {
    foreach ($_POST['copiestoname'] as $key=>$value) {
    $copiestoname = mysql_real_escape_string($value);

        mysql_query("INSERT INTO copiesto (name) VALUES ('$copiestoname')") or die(mysql_error());
        echo "Completed";
    }
echo "" . count($_POST['copiestoname']) . " Names Added<br>";
mysql_close();
}

The table in the database is:

Table Name: copiesto
+-------------+-------------+-------------+---------+
| index       |  name       | institution | method  |
+-------------+-------------+-------------+---------+

How would I expand the current MYSQL code to accept entries from the other 2 arrays and input their data into the same MYSQL row during that loop?

Upvotes: 1

Views: 4755

Answers (1)

Biswajit Maji
Biswajit Maji

Reputation: 889

you can use for loop instead

for ($i=0; $i < count($_POST['copiestoname']); $i++ ) {
  $copiestoname = mysql_real_escape_string($_POST['copiestoname'][$i]);
  $copiestoinst = mysql_real_escape_string($_POST['copiestoinst'][$i]);
  $copiestomethod = mysql_real_escape_string($_POST['copiestomethod'][$i]);

  mysql_query("INSERT INTO copiesto (name, institution, method) VALUES ('$copiestoname', '$copiestoinst', '$copiestomethod')") or die(mysql_error());
  echo "Completed";
}

Upvotes: 4

Related Questions