Get Multiple Checkbox Values in PHP

In this tutorial we are going to see how to get multiple checkbox values in PHP and store it in one column in database.

This is very common question asked by readers that how to Add multiple checked check boxes values into Mysql Database Table by using PHP.

If we want to get value of single checked checkbox, then easily get by post method but if we have multiple checkbox then
newbie coders face issue.

To get value of multiple checkbox, we have to inialize name attribute in HTML as an array by writing [] at the end of name
attribute.

So, let’s dive in.

Step 1: Create an HTML form with multiple checkbox

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

Step 2: PHP Script to Get Selected Checkbox Values and Save in Database

<?php if(isset($_POST['submit'])) 
{
$host = "localhost";
$username = "root";
$password = "";
$dbname = "pcluinfo";
$tbl_name = "language_list";

$conn = mysqli_connect("$host", "$username", "$password","$dbname")or die("cannot connect");

if(!empty($_POST['check_list'])){
$chk = implode(",", $_POST['pl']);
$query = "INSERT INTO language_list(name) values ('$chk')"; if(mysqli_query($conn, $query))
{
echo "Added Successfully";
echo "You have selected: ".$chk;
} else {
echo Failed To Add";
}
}else{
echo "Please Select Programming Language";
} }
?>

Conclusion

You have learned how to get values of multiple checked checkboxes using PHP. Once you have got the values, you can perform the CRUD operations in the database.

If you have any query feel free to write in the comment box.

Leave a Comment