简体   繁体   English

具有无限字段的表格

[英]Form With Unlimited Fields

我正在尝试通过PHP提交的表格形式的模型

I have a form that has an [Add Fields] option making it possible to add virtually unlimited Item Numbers and Descriptions. 我有一个带有[添加字段]选项的表格,可以添加几乎不受限制的项目编号和描述。

These fields are named: item[] and desc[] (brackets for arrays). 这些字段的名称为: item[]desc[] (数组的括号)。

My question is, how would I submit this information with PHP and MySQL so that each row (item and description) is submitted as it's own row in the database? 我的问题是,我将如何使用PHP和MySQL提交此信息,以便每一行(项目和描述)都作为数据库中的自己行提交?

I've tried multiple methods like submitting item[0] and desc[0] together with no avail :( 我尝试了多种方法,例如提交item [0]和desc [0],但都无济于事:(

Thanks for all of your help in advance! 感谢您提前提供的所有帮助!

EDIT: Below is what I've been trying to use... (Sorry, not that great with arrays...) 编辑:以下是我一直在尝试使用的...(对不起,数组不那么好...)

$count = 0
foreach ($_POST['item'] as $item) {
    $query = "INSERT INTO items (item, desc) VALUES ('" . $item[$count] . "', '" . $_POST['desc'][$count] . "')";
        // Script simplified as it is quite complex.
    if ($query_result) {
        $count++;
    }
}

you can loop through any one of the input field using foreach loop and then access other fields. 您可以使用foreach循环遍历任何输入字段,然后访问其他字段。

foreach($_POST['item'] as $key => $item){
    //your code
    $desc = $_POST['desc'][$key];
}

EDIT : as per your code script will be like 编辑:根据您的代码脚本将像

$count = 0
foreach ($_POST['item'] as $key => $item) {
    $query = "INSERT INTO items (item, desc) VALUES ('" . $item . "', '" . $_POST['desc'][$key] . "')";
        // Script simplified as it is quite complex.
    if ($query_result) {
        $count++;
    }
}

To further help you out, I might suggest the following. 为了进一步帮助您,我可能建议以下内容。

Name your fields like so: 像这样命名您的字段:

line[1][item]
line[1][desc]

line[2][item]
line[2][desc]

etc...

Then in PHP the data will make more 'sense' when viewing it: 然后在PHP中,查看数据时,数据将变得更加“有感觉”:

<?php
$count = 0;
foreach ($_POST['line'] as $line => $vals) {
  $item = $vals['item']; /* do some kind of input validation here */
  $desc = $vals['desc']; /* do some kind of input validation here */

  /* if no errors, continue */

  $sql = "INSERT INTO `items` (`item`,`desc`) VALUES ('$item', '$desc')";
  if (mysql_query ($sql)) {
    $count++;
  }
}
?>

I find this method to be more flexible. 我发现此方法更加灵活。 Just my two cents. 只是我的两分钱。

Luke 路加

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM