save multiple values of checkbox in database

2019-09-02 08:39发布

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>    

backend code is

<?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);
            }  

    } 

?>

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.

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

Whereas i wish to save the value as

id  sectorid
1      A
2      B

2条回答
爷、活的狠高调
2楼-- · 2019-09-02 09:01

Build the query like -

Implode them with brackets () -

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

Then pass it to the query -

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

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

查看更多
走好不送
3楼-- · 2019-09-02 09:06

Try this:

<?php
include('a_session.php');
require 'connection.php';
$sectorids = $_POST['sectorid'];
if(isset($_POST['sectorid']))
    {
        foreach($sectorids as $sectorid){
           $sql="INSERT INTO vendor_sector(sectorid) VALUES ('$sectorid')";
           if (mysqli_query($con, $sql)) 
               {
                   echo "success";
               } 
           else
               {
                   echo "Error updating record: " . mysqli_error($con);
               }  
           }
        }
    } 
?>
查看更多
登录 后发表回答