You can insert multiple checkbox values at a time using the foreach loop and array. We create multiple checkboxes to give multiple options. First of all, we create an MYSQL database table. We take three fields - id, language title, and post id. The post id can be any page id or other id. You can make it dynamic.
How to insert multiple checkbox values in PHP?
We can insert multiple checkbox values using the array. First of all, we create an MYSQL database table.
CREATE TABLE `languages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`langTitle` varchar(100) DEFAULT NULL,
`postId` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
In the table above, we have created three fields. The "langTitle" column will be used to insert values from the HTML checkboxes.
Let's create an HTML form containing multiple checkboxes.
<form action="" method="post">
Languages:<br>
<label>HTML </label><input type="checkbox" name="langTitle[]" value="HTML">
<label>C Programming</label><input type="checkbox" name="langTitle[]" value="C Programming">
<label>Java</label><input type="checkbox" name="langTitle[]" value="Java">
<input type="submit" value="Submit" name="submit_form">
</form>
There are three HTML checkboxes inside the HTML form tag. As you can see, we created an array to put all the checked values in the same array. We will hold the array using PHP POST method and loop by foreach() loop while inserting data into the MYSQL database
Let's hold the data and insert it into the database.
<?php
$databaseHost = 'localhost';
$databaseName = 'tute';
$databaseUsername = 'root';
$databasePassword = '';
$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);
if(isset($_POST['submit_form']))
{
$langTitle = $_POST['langTitle'];
$postId=12;//Set your post id
foreach ($langTitle as $lang) {
$result = mysqli_query($mysqli,"INSERT INTO languages(langTitle,postId) values('$lang','$postId')");
}
if($result)
{
echo "Inserted Successfully.";
}
else{
echo "Something went wrong.";
}
}
?>
You can make postid dynamic according to your need. In the code above, we created a connection using mysqli_connect() function. You can use the OOPS concept here. We hold the data by PHP post method and insert using the foreach loop. In this way, you can insert multiple checkbox data using PHP and MYSQL.