PHP:如何从HTML表中检测行号和列号?

时间:2016-07-11 08:15:45

标签: php html mysql

所以,我有一个带有HTML表的表单。

表格的每个框都包含一个文本字段。每个字段都具有相同的名称:

<input name="quantity[]" type="text" />

HTML表格如下所示:

html table with text fields

行是数字。列是月。 用户必须在最少一个方框中输入一个数字(数量)。

然后,他们可以提交表格。

我的SQL表应该是这样的:

Number - Month - Quantity
222000 - 12 - 50
222000 - 02 - 31
300000 - 01 - 25
221000 - 02 - 28

如您所见,我的表格中的1行= 1个输入文本。

在PHP中,我得到的数据如下:

foreach($_POST['quantity'] as $key => $text_field){
    if(!empty($text_field)) {
        $requete = $bdd->prepare('INSERT INTO my table VALUES(:number, :month, :quantity)');
        $requete->execute(array(
            ':number' => *???*,
            ':month' => *???*,
            ':quantity' => $text_field
        ));
    }
}

我的问题:如何从PHP中的HTML表中检测行号和列号,并将结果放入我的SQL表中?

3 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

填充表格时:

<input name="quantity[<?= $row ?>][<?= $column ?>]" type="text" />

然后在你的帖子处理程序脚本中:

foreach($_POST['quantity'] as $row => $columns){
    foreach ($columns as $column => $text_field) {
        if(!empty($text_field)) {
            $requete = $bdd->prepare('INSERT INTO my table VALUES(:number, :month, :quantity)');
            $requete->execute(array(
               ':number' => $row,
               ':month' => $column,
               ':quantity' => $text_field
             ));
        }
    }
}

简而言之,你将post字段设为关联数组而不是普通字段。

答案 1 :(得分:1)

假设您有12个飞蛾和数组“数字”,每行有数字值:

foreach($_POST['quantity'] as $key => $text_field){
if(!empty($text_field)) {
$number= $numbers[floor($key/12)];
$month=($key%12)+1;


    $requete = $bdd->prepare('INSERT INTO my table VALUES(:number, :month, :quantity)');
    $requete->execute(array(
        ':number' => $number,
        ':month' => $month,
        ':quantity' => $text_field
    ));
}

}

不要忘记0个索引。

答案 2 :(得分:0)

<?php
$n=1;
$num = array(111,222,333,...);

foreach($num as $key=>$n_val)
{
?>
<tr>
 <td>
   <input type="hidden" name="number[<?php echo $key ?>]" 
      value='<?php echo $n_val ?>'/>
   <?php echo $n_val ?>
 </td>
 <td><input name="quantityNov[<?php echo $key ?>]" type="text" /></td>
 <td><input name="quantityDec[<?php echo $key ?>]" type="text" /></td>
 ....
</tr>
<?php
}
?>

然后在php的提交操作部分;

<?php
    foreach($_POST['quantityNov'] as $key => $val)
    {
       $fixed_number = $_POST['number'][$key];
       $month[11] = $val;
       $month[12] = $_POST['quantityDec'][$key];
       $month[1] = $_POST['quantityJan'][$key];
       ...
       $count = 0;
       foreach($month as $month_num=>$n_val)
        if(!empty($n_val)) 
       {
            $sql = 'INSERT INTO my table (column(s)) VALUES ('.$fixed_number.','.$month_num.', '.$n_val.')';
            $result = $connection->query($sql);
            $count += $connection->affected_rows;
        }
    }
echo 'Number of rows inserted: '.$count;
?>

这就是我喜欢编写代码的方式,但你可以用自己喜欢的方式编写代码,但我认为这样可以帮助你。