【问题标题】:form checkbox value php表单复选框值php
【发布时间】:2014-07-09 15:41:43
【问题描述】:

我有一个由 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 等...
消息说存在错误的行是标记的行。

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

【问题讨论】:

  • 您的复选框没有名称属性,因此您将无法在表单提交/发布时访问它们。
  • 我应该在名称字段中输入什么?所有复选框或 $i 的名称相同?
  • 你会使用$i,就像你使用$_REQUEST[$j] -> name='".$i."'

标签: php arrays forms checkbox


【解决方案1】:

不要尝试这样做,这只会使处理变得困难,只需使用分组名称数组:name="checkboxes[&lt;?php echo $i; ?&gt;]",然后在提交时,所有检查的值都应该简单地转到$_POST['checkboxes']。想法是这样的:

<!-- 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" />

将处理表单的 PHP:

if(isset($_POST['submit'], $_POST['nid'])) {
    $ids = $_POST['nid']; // all the selected ids are in here
    // the rest of stuff that you want to do with it
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 2011-02-08
    相关资源
    最近更新 更多