简体   繁体   中英

Save checkbox selected value to database PHP

I have developed a program to save the checked value of the checkbox to the database.

The selected value is not passing to the database properly. There are no syntax errors in the code.

<?php
$link = mysqli_connect("localhost", "root", "123456", "database");

// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>

<form action="#" method="post">
<input type="checkbox" name="check_list[]" value="C/C++"><label>C/C++</label><br/>
<input type="checkbox" name="check_list[]" value="Java"><label>Java</label><br/>
<input type="checkbox" name="check_list[]" value="PHP"><label>PHP</label>  <br/>
<input type="submit" name="submit" value="Submit"/>

</form>

<?php

if(isset($_POST['submit']))
{//to run PHP script on submit
    if(!empty($_POST['check_list']))
        {
            foreach($_POST['check_list'] as $selected)
                {
                    if(isset($_POST['PHP'])) {
                $stmt = $link->prepare('INSERT INTO `checkbox` (`php_value`) VALUES ($selected)');
                        $stmt->bind_param('s', $stmt);
                        $stmt->execute();

                    }



} // if(isset($_POST['submit']))

    mysqli_close($link);
                }
        }


?>

$_POST['PHP'] doesn't exist to be checked, that's why checkbox values don't save to database.

Changed:

if(isset($_POST['PHP']))

With:

 if($selected!="") {

Updated Code:

<?php
$link = mysqli_connect("localhost", "root", "123456", "database");

// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>

<form action="" method="post">
<input type="checkbox" name="check_list[]" value="C/C++"><label>C/C++</label><br/>
<input type="checkbox" name="check_list[]" value="Java"><label>Java</label><br/>
<input type="checkbox" name="check_list[]" value="PHP"><label>PHP</label>  <br/>
<input type="submit" name="submit" value="Submit"/>

</form>

<?php

if(isset($_POST['submit']))
{//to run PHP script on submit
    if(!empty($_POST['check_list'])) {
        foreach($_POST['check_list'] as $selected) {
            if($selected!="") {
                $stmt = $link->prepare('INSERT INTO `checkbox` (`php_value`) VALUES (?)');
                $stmt->bind_param('s', $selected);
                $stmt->execute();
                $stmt->close();
            }
        }

        mysqli_close($link);
    }
}


?>

Also added proper indentation for readability.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM