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 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序