duanfan5012 2012-12-02 17:31
浏览 27
已采纳

在表单中传递多行输入并在PHP中迭代它们?

I'm guessing this has been asked before, but I did some searching and haven't been able to find an answer (probably because of my lack of terminology).

I'm working on an application that displays a bunch of rows of inputs in a table and when the form is submitted I need to iterate over every input updating the database with the input's value. What I've been doing is naming inputs like this:

<input type="text" name="name1"><input type="text" name="gender1"> ...
<input type="text" name="name2"><input type="text" name="gender2"> ...
<input type="text" name="name3"><input type="text" name="gender3"> ...
.
.
.

Then in PHP doing this:

for($i = 1; isset($_POST['name' . $i]); $i++)
{
    $name = $_POST['name' . $i];
    $gender = $_POST['gender' . $i];
    // update DB with input values
}

In my application rows can be added and deleted, there are about 6 inputs in each row, and often dozens of rows. This just seems kind of messy to me and I'm wondering if there is a better/cleaner way of doing it?

  • 写回答

1条回答 默认 最新

  • dongyun3897 2012-12-02 17:36
    关注

    Better to use following way by taking HTML input array

    <input type="text" name="name[]">
    <input type="text" name="gender[]">
    

    In PHP, you have to do following

    $cnt = count($_POST['name']);
    for($i=0;$i<$cnt;$i++){
       echo $_POST['name'][$i];
       echo $_POST['gender'][$i];
       ....
       // do any update with database
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里