Izu
Izu

Reputation: 52

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


?>

Upvotes: 1

Views: 77

Answers (1)

Karlo Kokkak
Karlo Kokkak

Reputation: 3714

$_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.

Upvotes: 2

Related Questions