【问题标题】:Working with checkbox from form array in php在php中使用表单数组中的复选框
【发布时间】:2016-05-18 17:11:30
【问题描述】:

我将产品从产品表中循环出来以将它们添加到购物车表中。仅应添加通过选中复选框选择的产品,但如果您选择,则选择的产品不对应.. 这是获取产品的 HTML

<html>     
    <form action="#" id="" class="horizontal-form" method="post">
    <?php
    $LISTP = "SELECT * FROM products ORDER BY id";          

$sn = 0;
                    $stmt = $pdo->prepare($LISTP);
                    $stmt->execute();

                    while($list = $stmt->fetch(PDO::FETCH_ASSOC)){
                    $sn = $sn + 1;
                    $ID = $list['id'];
                    $NAME = $list['name'];
                   ?>
                     <input type="checkbox" name="slected[]" class="checkboxes" value="1" /> 
                     <input type="hidden" name="productid[]" class="" value="<?php echo $ID;?>" />
                     <input type="text" name="name[]" class="" value="<?php echo $NAME;?>" />
                    <?php }?> </form>

<?php 
// now when we submot the form
$slected = $_POST['slected'];
$prod = $_POST['productid'];
$name = $_POST['name'];

foreach($prod as $key => $product){
if($slected[$key]>0){

echo $product.' '.$name[$key].' '.@$slected[@$key].'--<br>';
}

// the problem is here, if you check all product it will work well, but if            you check the second one
// it would echo the second one giving it the name of the first one which     was not checked at all 
?>

【问题讨论】:

  • 你试过var_dump($key, $product, $slected[$key])吗?这样做,看看你的代码有什么问题。

标签: php html checkbox


【解决方案1】:

我过去曾经这样做过,并且发现了我认为更好的方法。不用隐藏输入来存储 ID,只需使用 ID 作为所有表单变量键的索引:

<input type="checkbox" name="slected[<?php echo $ID; ?>]" class="checkboxes" value="1" /> 
<input type="text" name="name[<?php echo $ID; ?>]" class="" value="<?php echo $NAME;?>" />

那么,你的 PHP 就可以简化了:

// now when we submot the form
$slected = $_POST['slected'];
$name = $_POST['name'];

foreach( (array)$slected as $ID => $on ) {
    echo $product . ' ' . $name[$ID] . ' ' . $ID . '--<br>';
}

所以 - 基本上,您的 $slected 变量将包含一个仅包含选定项目的数组,并且您在 $slected 数组中内置了产品 ID。

【讨论】:

    猜你喜欢
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 2015-07-23
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    相关资源
    最近更新 更多