多个值插入复选框只有最后一个值在数据库中

时间:2017-12-14 05:21:28

标签: php html mysql arrays

我需要在复选框中插入多个值,但现在似乎只是输入的最后一个值是插入数据库。

这是我的HTML代码

<input id="option5" type="checkbox" name="product[]"  value="<?php echo $result["software"];?>"> 

<label for="option5"><span><span></span></span><?php echo $result["software"];?></label>

和插入代码是

$array = array($_POST['product']);            
$value = implode(',', $array);        
echo $value;

3 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你正在寻找这样的事情: -

$array= array(
'0' => 123,
'1' => 456,
'2' => 789, 
); // this is your post product array oryou want to get last value of that arrray
    -----Or----
$array = $_POST['product']; // your post data after submission

end($array);         // move the internal pointer to the end of the array
$key = key($array);  // fetches the key of the element pointed to by the internal pointer
echo $array[$key]; // 789

希望它有所帮助!

答案 1 :(得分:0)

您的问题可能是:

您有多个复选框。

并且您想将所有这些插入数据库。

您需要循环发布的复选框。

您的问题可能是您没有遍历$_POST['product'],因此,只有最后一个产品才会插入数据库。

所以,你的复选框:

<input id="option5" type="checkbox" name="product[]"  value="<?php echo $result["software"];?>">
<label for="option5"><span><span></span></span><?php echo $result["software"];?></label>

发布文件的代码:

if (! empty($_POST['product'])) {
 foreach ($_POST['product'] as $product) {
  // Here, you insert $product into database.
 }
}

答案 2 :(得分:0)

如果要在数据库中保存多个值,则需要在html中创建多个复选框,然后使用implode()方法保存值,如下所示: -

<input id="option1" type="checkbox" name="product[]"  value="value1">
<label for="option1">Value1</label>
<input id="option2" type="checkbox" name="product[]"  value="value2">
<label for="option2">Value2</label>
<input id="option3" type="checkbox" name="product[]"  value="value3"> 
<label for="option3">Value3</label>

现在要存储在数据库中,你可以使用implode()方法。

$values=implode(",",$_POST['product']);

现在将$值存储在数据库中。

相关问题