简体   繁体   English

PHP表单处理,仅填写字段

[英]PHP Form Processing with only filled in fields

I have a PHP class which have 8 properties and a HTML form which have 40 (8*5) textboxes, 8 per object, so a user can enter data for 5 objects at once. 我有一个具有8个属性的PHP类和一个具有40个(8 * 5)文本框的HTML表单,每个对象8个,因此用户可以一次输入5个对象的数据。

For each set of boxes I want to create an object of the class and save it into my database. 对于每组盒子,我想创建该类的一个对象并将其保存到我的数据库中。 If the user for example have filled in 10 boxes (two sets), two objects should be created and saved. 例如,如果用户已填写10个框(两组),则应创建和保存两个对象。

If i understand you correctly, here is HTML form example: 如果我正确理解您的意见,以下是HTML表单示例:

<form action="" method="post">
  <fieldset>
    <legend>Group 1</legend>
    <div>
      <input type="text" name="groups[0][first_name]" />
    </div>
    <div>
      <input type="text" name="groups[0][last_name]" />
    </div>
  </fieldset>

  <fieldset>
    <legend>Group 2</legend>
    <div>
      <input type="text" name="groups[1][first_name]" />
    </div>
    <div>
      <input type="text" name="groups[1][last_name]" />
    </div>
  </fieldset>

  <fieldset>
    <legend>Group 3</legend>
    <div>
      <input type="text" name="groups[2][first_name]" />
    </div>
    <div>
      <input type="text" name="groups[2][last_name]" />
    </div>
  </fieldset>
</form>

Pay attention to field names, how fields are grupped. 注意字段名称,字段如何聚集。 After submitting form like this, your $_POST superglobal array will contain $_POST['groups'] array of following structure: 提交这样的表单后,您的$ _POST超全局数组将包含以下结构的$ _POST ['groups']数组:

Array
(
    [0] => Array
        (
            [first_name] => 
            [last_name] => 
        )

    [1] => Array
        (
            [first_name] => 
            [last_name] => 
        )

    [2] => Array
        (
            [first_name] => 
            [last_name] => 
        )

)

You can easily process such data with code like this: 您可以使用以下代码轻松处理此类数据:

foreach ($_POST['groups'] as $group) {
  $group = array_filter($group);

  if (!empty($group)) {
    // do something with group
  }
}

This little example loops through all submitted groups. 这个小例子遍历所有提交的组。 array_filter() function will throw away all empty values from each $group array, and !empty(...) will make sure that $group is not empty. array_filter()函数将丢弃每个$ group数组中的所有空值,!empty(...)将确保$ group不为空。

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

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