Get checked Checkboxes value with PHP

Checkboxe­s are a versatile tool found on many we­bsites, allowing users to sele­ct their preferre­d choices among different options available­ with ease.

When you use it in your form and try to read all checked values as any other elements like –  text box, text area, radio button, etc.

echo $_POST['lang'];  // Checkbox element

you will get the last checked value.

You need to send the checkboxes value in the form of an Array when the form gets submitted then you can loop over $_POST values.

In this tutorial, I show how you can read submitted checked checkboxes values with PHP and also show how you can save it to the MySQL database.

Get checked Checkboxes value with PHP


Table of content

  1. Read $_POST checked values
  2. Demo
  3. Create a Table to save checked checkboxes values
  4. Database Configuration
  5. Insert and Display checked values from Database
  6. Conclusion

1. Read $_POST checked values

HTML

While creating multiple checkboxes add [] at the end of name attribute e.g. lang[]. Here, [] denotes an Array.

<span>Select languages</span><br/>
<input type="checkbox" name='lang[]' value="PHP"> PHP <br/>
<input type="checkbox" name='lang[]' value="JavaScript"> JavaScript <br/>
<input type="checkbox" name='lang[]' value="jQuery"> jQuery <br/>
<input type="checkbox" name='lang[]' value="Angular JS"> Angular JS <br/>

PHP

When the form is submitted then loop over $_POST checkbox name using foreach.

if(isset($_POST['submit'])){

    if(!empty($_POST['lang'])) {    
        foreach($_POST['lang'] as $value){
            echo "value : ".$value.'<br/>';
        }
    }

}

Full Code

<form method="post" action="">
    <span>Select languages</span><br/>
    <input type="checkbox" name='lang[]' value="PHP"> PHP <br/>
    <input type="checkbox" name='lang[]' value="JavaScript"> JavaScript <br/>
    <input type="checkbox" name='lang[]' value="jQuery"> jQuery <br/>
    <input type="checkbox" name='lang[]' value="Angular JS"> Angular JS <br/>

    <input type="submit" value="Submit" name="submit">
</form>

<?php
if(isset($_POST['submit'])){

    if(!empty($_POST['lang'])) {

        foreach($_POST['lang'] as $value){
            echo "value : ".$value.'<br/>';
        }

    }

}
?>

2. Demo

View Demo


3. Create a Table to save checked checkboxes values

I am using languages table in the example.

CREATE TABLE `languages` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `language` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

4. Database Configuration

Create config.php file for database configuration.

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

5. Insert and Display checked values from Database

Create an Array $languages_arr to store languages names.

Using this to create checkboxes by looping on it.

Insert checked checkboxes –

On <form> submit convert $_POST['lang'] to string using implode(). Check entry in languages table if not exists then insert $lang in the table otherwise, update language value.

Display checked checkboxes –

Fetch record from languages table. If a record exists then explode $result['language'] to get an Array and assign in $checked_arr.

While looping on $languages_arr Array check $language value exists in $checked_arr Array. If exists then assign "checked" to $checked and use in the checkbox creation.

<?php
include "config.php";
?>
<!doctype html>
<html>
<head>
    <title>Get checked Checkboxes value with PHP</title>
    <?php
    if(isset($_POST['submit'])){

         if(!empty($_POST['lang'])) {

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

              // Insert and Update record
              $checkEntries = mysqli_query($con,"SELECT * FROM languages");
              if(mysqli_num_rows($checkEntries) == 0){
                   mysqli_query($con,"INSERT INTO languages(language) VALUES('".$lang."')");
              }else{
                   mysqli_query($con,"UPDATE languages SET language='".$lang."' ");
              }
 
         }

    }
    ?>
</head>
<body>
    <form method="post" action="">
         <span>Select languages</span><br/>
         <?php

         $checked_arr = array();

         // Fetch checked values
         $fetchLang = mysqli_query($con,"SELECT * FROM languages");
         if(mysqli_num_rows($fetchLang) > 0){
               $result = mysqli_fetch_assoc($fetchLang);
               $checked_arr = explode(",",$result['language']);
         }

         // Create checkboxes
         $languages_arr = array("PHP","JavaScript","jQuery","AngularJS");
         foreach($languages_arr as $language){

              $checked = "";
              if(in_array($language,$checked_arr)){
                   $checked = "checked";
              }
              echo '<input type="checkbox" name="lang[]" value="'.$language.'" '.$checked.' > '.$language.' <br/>';
         }
         ?>
 
         <input type="submit" value="Submit" name="submit">
    </form>

</body>
</html>

6. Conclusion

Next time when you use multiple checkboxes in your form then just initialize the name as an Array by putting [] in front and read it with loop when submitted.

Use implode() to convert checked values Array to string and store it in your MySQL database.

If you found this tutorial helpful then don't forget to share.