简体   繁体   中英

How to store multiple checkbox values in multiple columns of same table in database using PHP?

In below code, I am selecting 4 checkboxes and I am able to display those 4 selected checkboxes. But how to store those 4 selected checkbox values in different columns under lecture1, lecture2 and so on in same table of my database. 4 is default value for checkbox of lectures.

$teachername1=$_POST[ 'teachername1' ];
echo"$teachername1";
$_SESSION['teachername1']=$_POST[ 'teachername1' ];
if(!empty($_POST['lecture']))
{
   $checked_count = count($_POST['lecture']);
   echo"You have selected following ".$checked_count."option(s):<br/>";
   foreach($_POST['lecture'] as $selected)
   {
      echo $selected."<br>";
   }
}    

You have not posted the table structure but anyways I will try to give my best suggestions here.

Existing System:

You have 4 choice columns in your tables for eg:

Make all 4 columns as boolean to check whether they are set(1) or not set(0) by inserting 1 or 0 respectively to keep track whether they have selected the choice or not.

id,(other columns),choice1, choice2, choice3, choice4

Make sure whenever you insert the check box selected values while inserting into database table set 1 or 0 to the respective tables.

When you fetch the records for the respective row if the column is set to 1 then that checkbox was selected.

There is problem with the system what you have. Please use the following way.

Suggested Way:

Please don't store the checkbox values in different columns. Today you may have only 4 values. Think in future you may come up with 8 checkboxes. In that case you need to add 4 more columns.

Instead of that you can normalize your database table by having one more table with respective name. Now your new normalized table looks like

checkbox table
--------------

id, checkbox_name, checkbox_value(if any)

teachers table
--------------

id, cols (other columns which I dont know whether its there or not)

teachers_choices //This is the checkbox selected table
----------------

id, teacher_id(this references to teacher table), checkbox_id (this references to checkbox table)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM