使用PHP中的表单数组的复选框 [英] Working with checkbox from form array in php

查看:81
本文介绍了使用PHP中的表单数组的复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将产品从产品表中循环,以将其添加到购物车表。只有选中的产品通过选中复选框应该添加,但如果您选择,所选择的不对应。
这里是HTML获取产品

Am looping products out from product table to add them to cart table. only the selected product by checking the checkbox should be added, but if you select, the selected ones do not correspond.. HERE IS THE HTML GETTING THE PRODUCTS OUT

<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 
?>


推荐答案

,并发现我认为是一个更好的方法。只需使用ID作为所有表单变量键的索引,而不是具有存储ID的隐藏输入:

I used to do this the same way in the past, and have discovered what I think is a better way. Rather than having a hidden input that stores the ID, just use the ID as the index for all of the form variable keys:

<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可以简化:

Then, your PHP can be simplified:

// 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 变量将包含仅选择项目的数组,并且您的产品ID内置在$ slected数组中。

So - basically, your $slected variable will contain an array of only items that are selected, AND you have the product ID built in to the $slected array.

这篇关于使用PHP中的表单数组的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆