通过php将复选框中的多值插入数据库

时间:2011-06-18 07:39:12

标签: php database checkbox insert

我希望将此表单值插入datanase:

<input type="checkbox" name="brand1" id="brand1" value="1"> <label for="brand1">Brand 1</label>
<input type="checkbox" name="brand2" id="brand2" value="1"> <label for="brand2">Brand 2</label>
<input type="checkbox" name="brand3" id="brand3" value="1"> <label for="brand3">Brand 3</label>
<input type="checkbox" name="brand4" id="brand4" value="1"> <label for="brand4">Brand 4</label>
<input type="checkbox" name="brand5" id="brand5" value="1"> <label for="brand5">Brand 5</label>

这些文本框是通过php从数据库中的表中获取的,可能是Variable

我想通过这种格式插入数据库 如果品牌1被检查$ brand =“1,”;

最后是这样的:

insert($name,$brands); and $brands = "1,2,3,4,5,";

如果用if和while写这个但是它不起作用,因为如果插入运行时{}五次插入Done并且插入用尽了{},$ brand =“5,”

感谢您对此问题的帮助或想法

这意味着:

<form method="post" action="#">
<?php
$result = $db->getall(brands);
        if(!empty($result)) {
    while ( list($key,$val)=each($result) ) {
        $brand_id = stripslashes($val["id"]);
        $brand_name = stripslashes($val["name"]);
    ?>
    <input type="checkbox" name="brand<?php print"$brand_id"; ?>" value="1" style="cursor:pointer;"><label for="brand<?php print"$brand_id"; ?>" style="cursor:pointer;"> <?php print"$brand_name"; ?></label>
    <?php }} ?>

来源输出:

<input type="checkbox" name="brand1" value="1"> <label for="brand1">Brand Name 1</label>
<input type="checkbox" name="brand2" value="1"> <label for="brand2">Brand Name 2</label>
<input type="checkbox" name="brand3" value="1"> <label for="brand3">Brand Name 3</label>
<input type="checkbox" name="brand4" value="1"> <label for="brand4">Brand Name 4</label>
<input type="checkbox" name="brand5" value="1"> <label for="brand5">Brand Name 5</label>
<input type="submit" value="Submit" />
</form>

提交表单时,插入源代码为:

    <?php
$result = $db->getall(brands);
        if(!empty($result)) {
    while ( list($key,$val)=each($result) ) {
        $brand_id = brand.stripslashes($val["id"]);
        $brand_name = stripslashes($val["name"]);
    $brand_ids = "brand.$brand_id";
    if($$brand_ids==1) {$brands="$brandid,"}

}} ?>
$db->add_submenu("$brands"); 

1 个答案:

答案 0 :(得分:2)

您应该将复选框的名称更改为brand[]。在$_POST['brand']

提交后,它会为您提供一个数组
Ex. 

<input type="checkbox" name="brand[]" value="1" ... />
<input type="checkbox" name="brand[]" value="2" ... />
<input type="checkbox" name="brand[]" value="3" ... />
<input type="checkbox" name="brand[]" value="4" ... />
<input type="checkbox" name="brand[]" value="5" ... />

另一方面,您可以执行以下操作:

// this will return '1, 2, 3, 4, 5' when all are selected. 
$index = implode(", ", $_POST['brand']); 

此时您将以逗号分隔的形式拥有品牌。