将输入类型文本放在数组中

时间:2013-11-18 22:14:26

标签: php html

我有一些text inputsinputs是从while循环生成的。现在我想把values放在一个数组中。像这样:

array       values
mark['0']   input1
mark['1']   input2
mark['2']   input3

我尝试了这个但不行。

while($row=mysql_fetch_array($result)){
  <form class="form1" name="form1" method="post">
    <input type="text" name="mark[]"/>
  </form>
}
<form class="form1" name="form1" method="post">
    <button type="submit" name="correction"></submit>
</form>

然后

if(isset($_POST['correction'])){
$grade=0;   
    $mark=$_POST['mark'];
    foreach($mark as $key =>$value ){
        $grade+=$value;
    }   
print $grade;
}

我收到这些错误:

Notice: Undefined index: mark in C:\xampp\htdocs\virtual_exam\handy_correction.php on line 37

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\virtual_exam\handy_correction.php on line 38

问题可能是由两种不相互连接的形式引起的,如果是,则如何加入它们? 如果不是,怎么做我想要的?

3 个答案:

答案 0 :(得分:2)

您应该只有一个表单元素,而不是您尝试输出的每一行都有一个,当然也不是表单提交按钮的单独元素。

您的问题是您提交的实际表单中只有一个元素 - 提交按钮。因此,根本没有输入字段可以发布。

您应该生成如下表单:

<form class="form1" name="form1" method="post">
<?php
while($row=mysql_fetch_array($result)){
?>
    <input type="text" name="mark[]"/>
<?php
}
?>
    <button type="submit" name="correction"></submit>
</form>

答案 1 :(得分:1)

将表单更改为:

<form class="form1" name="form1" method="post">

  <?php
    while ($row = mysql_fetch_array($result)) {
      echo '<input type="text" name="mark[]" />';
    }
  ?>

  <input type="submit" name="correction" value="Submit" />
</form>

然后:

if (isset($_POST['correction'])) {
  $grade = 0;   
  $mark  = $_POST['mark'];

  foreach ($mark as $key => $value) {
    $grade += $value;
  }

  echo $grade;
}

答案 2 :(得分:-1)

你说的最后一段是正确的,你提交的form1只包含提交按钮,因此处理POST的PHP脚本中不存在mark

所以将HTML更改为:

<form class="form1" name="form1" method="post">
<?php
while($row=mysql_fetch_array($result)){
?>
    <input type="text" name="mark[]"/>
<?php
}
?>
    <button type="submit" name="correction"></submit>
</form>
相关问题