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

View Demo


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

If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

24 thoughts on “Get checked Checkboxes value with PHP”

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

      Reply
    • <?php
      if(isset($_POST['submit'])){
      $arr="";
      if(!empty($_POST['lang'])) {
      $counter=0;
      foreach($_POST['lang'] as $value){
      $arr.=$value;
      if ($counter!=count($_POST['lang'])-1) {
      $arr.=", ";
      }

      $counter++;
      }
      echo "array : ".$arr.'’;
      }

      }
      ?>

      // AND YOU CAN INSERT ALL CHECKED CHECKBOXES TO DATABASE AS ONE STRİNG BY USİNG THE CODE ABOVE

      Reply
  1. 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.

    Reply
  2. how can i get the array values from database ?????
    i mean in above Program languages are stored like this type
    “java, php , angular js”.
    when we selected checkbox then data will be shown
    Java
    PHP

    how can i get ?

    Reply
  3. Is it possible to update a database with the checked values without using “form”?

    I have a table with one column that is a checkbox and I would like to pull everything from that row if it is checked.

    Reply
  4. Thats pretty good, but I’m kinda struggling…

    I have three checkboxes and I can’t uncheck every single one.

    So one has to be enabled, thats kind of bad, could you help me out there?

    Reply
  5. Hi,this is very useful. I have special request. I wanted to click the checkbox and it comes with a brief justification which is a text fill. how can i link both checkbox and text fill in the same row of database? I am using phpmyadmin for database

    Reply
  6. Buenas lo que me pasa a mi en mi proyecto, es que tengo varios Checkboxs,
    pero cuando me llega un mail desde mi web no se que han marcado los clientes, no ,e aparece, si asi los datos de ellos. Desde ya muchas gracias
    Adjunto URL para que lo puedas ver.

    Reply
  7. Hi, I want to have checkbox stored values each to represent an image from a different table. How can I assign and display? Example the checkbox values are dog cat bird. The dog cat bird are in a different table with the image file info stored for each animal. User checks what animal(s) they like which is stored in user database. When user profile pulled up under animals they like section the photos of the animal(s) they like displays. I can’t get it to work. I’m using a join, but tearing my hair out. Any suggestions would be greatly welcomed.

    Reply
  8. This is a very good overview. I am wanting to use checkboxes with data that is in an HTML table. The table is loaded with data, but the user may opt to change data or exclude a row by not checking the checkbox. How do I control the loading of data (for rows with a check) from the HTML table to insert into a MySQL table?
    My fields are (checkbox), orderId, productId, Description, Quantity, Price. I only need to load: orderId, productId, quantity and price

    My HTML table is loaded from a query of a MySQL view and the results will be inserted to another table.

    Reply
  9. good day all, please i want the values if matric_no and sup_no in this code to be inserted into another table called supervisors_students table.

    body,td,th {
    color: #000000;
    }
    body {
    background-color: #FDFFF0;
    }

    List of students

    Matric_Number
    First Name
    Last Name
    Other Name
    Department
    Faculty
    Year of Graduation
    Select

    <?php
    $query = mysqli_query($conn, "SELECT matric_no, FirstName,LastName, OtherName, Department, Faculty, YearofGraduation FROM students ORDER BY Department")
    or die (mysqli_error($conn));

    while ($row = mysqli_fetch_array($query)) {
    echo
    "
    {$row[‘matric_no’]}
    {$row[‘FirstName’]}
    {$row[‘LastName’]}
    {$row[‘OtherName’]}
    {$row[‘Department’]}
    {$row[‘Faculty’]}
    {$row[‘YearofGraduation’]}

    \n”;
    }
    ?>

    Reply

Leave a Comment