在数据库中保存复选框的多个值

问题描述:

我正在尝试从用户端表单中的数据库(即不同的行)中的复选框中保存多个值.我表单的代码是

i am trying to save multiple values from checkbox in database (i.e different rows) from user end form. code for my form is

<form action="a_insert_vendor_sector.php" method="post">

    <?php

    $sql = "SELECT * FROM sector where cityid='".$cityid."'";

    $sql1 = mysqli_query($con, $sql);
    if (mysqli_num_rows($sql1) > 0) 
        {
            while($row = mysqli_fetch_assoc($sql1)) 
                {
                    $sector = $row["sector"];
                    $sectorid = $row["id"];
                    echo $sector;
                    echo "<input type='checkbox' name='sectorid[]' value='$sector' >";
                    echo "<br>";
                }
        }

       ?>

    <footer>
        <div class="submit_link">
            <input type="submit" name="submit" value="Submit" class="alt_btn">
        </div>
    </footer>   
</form>    

后端代码是

<?php
include('a_session.php');
require 'connection.php';

$sectorid = implode(' ', $_POST['sectorid']);

if(isset($_POST['submit']))
    {       
        $sql="INSERT INTO vendor_sector(sectorid) VALUES ('$sectorid')";

        if (mysqli_query($con, $sql)) 
            {
                echo "success";
            } 
        else
            {
                echo "Error updating record: " . mysqli_error($con);
            }  

    } 

?>

原始表格视图vendor_sector

Original table view vendor_sector

id  sectorid
1     A

当我提交表单时,我会以这样的数组形式获取值

When i submit the form, i get the value in form of array like this

Array
(
    [0] => A
    [1] => B
)

因此这些值可以正确地携带到后端,但是我无法正确保存它们.

so the values are being carried properly till back end, but i am not able to save them properly.

我的问题是,如果我选择2个值(例如A,B),它们将像这样保存为一个值

My problem is that if i select 2 values e.g A,B they are getting saved as one value like this

id  sectorid
1     A,B

我希望将值另存为

id  sectorid
1      A
2      B

构建类似于-

用方括号()-

$sectorid = "('" . implode("') , ('", $_POST['sectorid']) . "')";

然后将其传递给查询-

$sql="INSERT INTO vendor_sector(sectorid) VALUES $sectorid";

此外,您还需要将implode放入$_POST支票中,就像未发布一样,这会导致错误.

Also you need to put the implode inside the $_POST check as if it is not posted then you will get error.