表单复选框值php

时间:2014-07-09 15:41:43

标签: php arrays forms checkbox

我有一个由php中的while循环创建的表单,如下所示:

<form action='#' method='post'>
<input type='hidden' name='form_valid' id='form_valid'>
<?php
$i=-1;
$result_array = array();
//the while is from a simple mysql query
while( $line = $results->fetch() )
{
  $i++;
  echo"<input type='checkbox' class='checkbox' value='".$line->nid."' id='".$i."'>";
  echo $line->title;
  echo'<br>';
  $result_array[$i] = $line->nid;
}
<input type='submit'>
?>
</form>

然后在代码中我想将复选框的值仅存储在一个新数组中:

if (isset($_REQUEST['form_valid'])) //checking is form is submitted
{
   foreach($result_array as $result)
   {
      if($result == $_REQUEST[$j])  <<<< ERROR
      {
        $final_array[$j] = $result;
      }
   }
 }

令人惊讶的是,这段代码根本不起作用 错误消息是“通知:未定义的偏移:0”,然后偏移1然后是2等...
消息显示错误的行是标记的行。

我真的不知道该怎么做。有人吗? =)

1 个答案:

答案 0 :(得分:0)

不要试图这样做,这只是让它很难处理,只需使用分组名称数组:name="checkboxes[<?php echo $i; ?>]",然后在提交时,检查的所有值应该只是去{{ 1}}。这是个主意:

$_POST['checkboxes']

将处理表单的PHP:

<!-- form -->
<form action="" method="POST">
<?php while($line = $results->fetch()): ?>
    <input type="checkbox" class="checkbox" name="nid[<?php echo $line->nid; ?>]" value="<?php echo $line->nid; ?>" /><?php echo $line->title; ?><br/>
<?php endwhile; ?>
<input type="submit" name="submit" />