Get checked Checkboxes value with PHP

The checkbox element in HTML allows us to select multiple items from the group of values.

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.

Get checked Checkboxes value with PHP


Contents

  1. Read $_POST checked values
  2. Demo
  3. Table structure
  4. 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 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/>';
        }
    }

}

Completed 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

Check the checkboxes and click the Submit button.


3. Table structure

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. Configuration

Create a new config.php file.

Completed Code

<?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 –

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 –

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 is exists in $checked_arr Array. If exists then assign "checked" to $checked and use in the checkbox creation.

Completed Code

<?php
include "config.php";
?>
<!doctype html>
<html>
  <head>

  <?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 just initialize 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 to your MySQL database.

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

Related Post

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  

5 Comments

  1. Ren said:

    how csn i insert it into the database?

    April 1, 2018
    Reply
    • Yogesh Singh said:

      Convert the checked values in a string format and store in a variable by implode() the $_POST[‘lang’] by ‘,’.
      implode(“,”,$_POST[‘lang’]);

      Use the variable in the INSERT query.

      April 1, 2018
      Reply
  2. Ilmal said:

    Good tutorial, thank u

    April 12, 2018
    Reply
  3. mega putra said:

    if (!empty($_POST[lang])){
    $langs = $_POST[lang];
    $lang=implode(‘,’,$langs);
    }
    I think this is the way to implode and store it to database using mysqli, an I right?
    Now, how to keep the checkbox checked after we store it to database? I could not figure it out. I’ve tried but it failed. However if I use mysqlm it worked, but when I change to mysqli, it failed. COuld you please share with us? Thanks Yogesh.

    May 15, 2018
    Reply
    • Yogesh Singh said:

      I have updated the tutorial and cover the topic – how to store and display checked values from the database.

      May 15, 2018
      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *