php - 如何从多个 $_POST 数组插入 MYSQL 行

标签 php mysql arrays forms

我有一个带有“添加联系人”部分的表单,单击该部分后,它会在表单中添加另一行以及另外 3 个输入框。 (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>

这是用于插入的 PHP/MYSQL:

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();
}

数据库中的表是:

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

我将如何扩展当前的 MYSQL 代码以接受来自其他 2 个数组的条目并在该循环期间将它们的数据输入到同一 MYSQL 行中?

最佳答案

你可以用for循环代替

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";
}

关于php - 如何从多个 $_POST 数组插入 MYSQL 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18665208/

相关文章:

php - 使用 session PHP 将登录详细信息传递到另一个页面

php - 访问网络托管服务上 phpMyAdmin 的权限

mysql - 如何从两个表中获取针对 ID (FK) 的多个图像

php - 在数组中设置嵌套项

javascript - 从数组中删除重复项

python - 有效地获得 3 个不同大小和类型的 numpy 数组的排列

php - PDO/MySQL 使用 if 语句获取多列

php - 我可以在 PHP 中混合使用 MySQL API 吗?

python - django.db.utils.OperationalError : (1045:Access denied for user 'root' @'localhost' (using password: NO)

MySQL 对 OR 的 3 个表的查询优化