【问题标题】:Looped Checkbox Array Value Repeated循环复选框数组值重复
【发布时间】:2017-10-15 08:16:27
【问题描述】:

我在一个 while 循环中有 4 个具有不同值的复选框并命名为一个数组。仅从最后循环的一组复选框中选择的值正在更新,但我需要将所有选定的值(每组 4 个 1 个)独立更新到它们对应的行。

HTML

<input type="checkbox" name="size[]" value="S" />
<input type="checkbox" name="size[]" value="M" />
<input type="checkbox" name="size[]" value="L" />
<input type="checkbox" name="size[]" value="XL" />

PHP

<?php
if(isset($_POST['update'])){
$select_id = "select * from customer where ip='$ip'";
$get_id = mysqli_query($db, $select_id);

while ($row = mysqli_fetch_array($get_id)){
foreach($_POST['size'] as $size){

$product_id = $row['product_id'];

$update_size = "update customer set size='$size' where product_id='$product_id'";
$run_size = mysqli_query($db, $update_size);
}
}
}
?>

更新 - 快到了!

退出循环

$i = 1;

在循环中

$i++;
<input type="checkbox" name="size[].$i." value="S" />
<input type="checkbox" name="size[].$i." value="M" />
<input type="checkbox" name="size[].$i." value="L" />
<input type="checkbox" name="size[].$i." value="XL" />

处理中

<?php
if(isset($_POST['update'])){
$select_id = "select * from customer where ip='$ip'";
$get_id = mysqli_query($db, $select_id);


while ($row = mysqli_fetch_array($get_id)){

$size = $_POST['size'];
$product_id = $row['product_id'];

foreach ($size as $_POST['size']);
{

$update_size = "update customer set size='$size' where product_id='$product_id'";
$run_size = mysqli_query($db, $update_size);
}
}
}
?>

现在每行更新不同的变量集,但现在一个是正确的值,另一个只是数组,但为什么?

【问题讨论】:

    标签: arrays loops checkbox


    【解决方案1】:

    根据代码,foreach 循环执行并更新大小字段,但每次更新语句运行时都会覆盖旧值。因此,最后一个循环复选框的值被存储。我认为您需要检查您的数据库结构。如果您为同一个 product_id 存储 4 个不同的值,您将需要创建一个不同的表(一对多关系)。希望这会有所帮助。

    【讨论】:

    • 对不起,我应该提到,只有一个复选框被选中,所以每行只存储 4 个值中的 1 个。
    • 您可以使用&lt;input type="radio" name="size[]" value="S" /&gt; 或在复选框上添加一个javascript,以在单击任何复选框时取消选中其他框。这是一个参考:jsfiddle.net/MQM8k
    • 我需要增加复选框的名称,以便下一个循环框是唯一的。
    【解决方案2】:

    我所要做的就是;

    $size = array_shift($_POST['size']);
    

    【讨论】:

      猜你喜欢
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 2013-04-19
      • 1970-01-01
      • 1970-01-01
      • 2013-06-23
      • 1970-01-01
      • 2016-04-14
      相关资源
      最近更新 更多