How to insert checked values from checkbox in mysql by php - php

There are many Subject in my database. I called them in a form in checkbox. When some checkbox checked, those value will go on my database in "select_subject" table in subject column. And when checked a radio button for course name, its value will go in "course" column. My mysql query and chackbox code was:
<?php
$result = mysql_query("SELECT * FROM vhsubject WHERE lid= 2");
while($row = mysql_fetch_array($result))
{
echo "<input type='checkbox' name='vhsubject[]' value=".$row['subject_name'].">" .$row['subject_name']."<br />";
}
?>
After checked and submit, my query was
<?php
if (isset($_POST['form'])) {
$query2 = "INSERT INTO select_subject (subject, course) VALUES ('$_POST[vhsubject]', '$_POST[course_radio]')";
$insert = mysql_query ($query2) or die(mysql_error());
if ($insert){
echo "Your registration is complete";
}
}
?>
But it doesn't work. Please help me;

Use Implode Function:
You can not store value in the form of an array in mysql, so first convert array into string by using implode function.
here is the example:
<input name="q1[]" type="checkbox" value="a1">Used e-mail<br>
<input name="q1[]" type="checkbox" value="a2">Used instant messenger & chat room<br>
<input name="q1[]" type="checkbox" value="a3">Made a purchase for personal use<br>
<input name="q1[]" type="checkbox" value="a4">Downloaded/Played a video game<br>
<input name="q1[]" type="checkbox" value="a5">Obtained news/information/current events<br>
<input name="q1[]" type="checkbox" value="a6">Looked for employment (Used classified listings)<br>
<input name="q1[]" type="checkbox" value="a7">Looked for recipes<br>
<input name="q1[]" type="checkbox" value="a8">Downloaded a movie<br>
and now use implode function:
<?php
$q1=implode(',', $_POST['q1']);
?>

Related

PHP (check or uncheck) a checkbox from Database

So I'm using a checkbox to insert data into MySql database.
When check it stores "finish"
When unchecked if stores "pending"
Now for an edit feature, I have to fetch and display the data from the database. I need the checkbox to be checked or unchecked if it is stored as finish or pending. Appreciate your help, thank you.
The code to fetch the data is shown below:
<?php
$query = ("SELECT * FROM ebook WHERE Eid='" . $Eid . "'");
$result = mysqli_query($con, $query);
$rows = mysqli_fetch_assoc($result);
?>
Displaying data and checkbox:
<html>
<input type="text" name="title" value="<?php echo $rows["Title"]; ?>">
<input class="tgl tgl-flip" id="chk" type="checkbox" name="chk" />
</html>
Put a condition echo inside the input.
<input class="tgl tgl-flip" id="chk" type="checkbox" name="chk" <?php if ($rows['status'] == 'finish') { echo "checked"; } ?>/>

set value on multiple row from column based on previous query php/mysql

running the following query ($box is yes or no from previous page):
$raw_results = mysqli_query($con,"
SELECT *
FROM `tbl_case`
WHERE `self_paid` ='$box'
AND `case_date_closed` BETWEEN '$startdate' AND '$enddate'
");
It displays all the fields correctly, and finishes with another checkbox
with the radio button below, if selected yes, it should set yes to paid_state on all previously returned $id'
<h1> Would you like to set these as paid to self ?
<form>
<form action="selfpaid.php" method="POST">
<input type="radio" name="state" value="yes" checked> Yes<br>
<input type="radio" name="state" value="no"> no<br>
<input type="submit" style="margin-left:80px; width:150px; height:30px;" value="Set state" />
</form>
<?php
if(isset($_POST['state']) && $_POST['state'] == "yes")
{
mysqli_query($con,"UPDATE tbl_case SET self_paid = 'yes' WHERE id = '$id'");
echo "Setting paid statesucessfull.";
}
else{
echo "paid_state not set";
}
?>
i am guessing it needs to be pulled from the db, and put all those $id in another array var, but i can;t figure out how, and then loop over that array .. can someone point me in the right direction ?

Select Value from DB Array inside check box input

Hello I am using various check boxes with different values and than storing the vales inside DataBase as all the checkboxes values are store inside Array
<input type="checkbox" value="Gym" id="details_10" name="utilities[]">
<input type="checkbox" value="Spa" id="details_11" name="utilities[]">
and than store in the database like: Gym, Spa.
Later I am making MySQL query inside edit form where I will be able to edit those and other parameters. For the other inputs I am using:
<?php if($row['data'] == 'Sample Data'){echo 'selected="selected"';}?>
In this case I would like to use something like the following:
<input type="checkbox" value="Gym" id="details_10" name="utilities[]"<?php if($row['utilities'] == 'Gym'){echo 'checked"';}?>>
Any help to achieve this result will be very welcome.
I've always used this in these cases.
<?php
if($row['utilities'] == 'Gym')
{
?>
<input type="checkbox" value="Gym" id="details_10" name="utilities[]" checked="checked">
<?php
}
else
{
?>
<input type="checkbox" value="Gym" id="details_10" name="utilities[]">
<?php
}
?>

How to get two or more values of selected check boxes?

I have a list of candidates for the position of Business Managers. The voter needs to select at least two candidates. I used check boxes in order that the voter can do multiple select. And when the voter clicks on next button to proceed voting to other positions , the two selected Business Manager should be carried..The problem is I can get the two but with the same Name.
For example:Voter selected
John Smith and Harry Potter
The result when i get the value is only the last person selected. I noticed in my check inbox I used only one name="choice" so it is not possible to get two....I cann assign different name for each check inbox when my list is static but in my case i used the dyanmic way to place them in array of check boxex which means they have the same name="choice"...I hope you understand my point...Please help me..Below is my code implementation..
Result of populating the list of check boxes:
$result = mysql_query($QUERY);
while($row = mysql_fetch_object($result)){
$Name = $row->Name;
$PLName = $row->PLName;
$CID = $row->CID;
echo '<tr><td>';
echo '<img src="fetchImage.php?CID=' . $CID . ' " alt="Candidate photo" width="150px" height="135px" style="border:2px solid silver;">';
echo '</td>';
echo '<td><div class="contact_info_title">' . $Name . '</div><br>';
echo $PLName . '<br><br>';
if(isset($_SESSION['VLPCCBusManager'])){
if($_SESSION['VLPCCBusManager'] == $CID){
echo '<input type="checkbox" name="Choice" value=' . $CID . ' Checked>Select </td></tr>';
}else{
echo '<input type="checkbox" name="Choice" value=' . $CID . '>Select </td></tr>';
}
}else{
echo '<input type="checkbox" name="Choice" value=' . $CID . '>Select </td></tr>';
}
}
echo '';
Getting the selected choices when submit is clicked moving to another form:
if(isset($_POST['submit'])){
if(isset($_POST['Choice'])){
if(empty($_POST['Choice'])){ $errors='Choice'; }
if(empty($errors)){
$Choice = $_POST['Choice'];
$_SESSION['VLPCCBusManager'] = $Choice;
$_SESSION['VLPCCBusManager2'] = $Choice;
header("Location: VLPCCSgtArms.php?ChoiceCat=$ChoiceCat");
}
}else{
$_SESSION['VLPCCBusManager'] = '0';
$_SESSION['VLPCCBusManager2'] = '0';
header("Location: VLPCCSgtArms.php?ChoiceCat=$ChoiceCat");
}
}
You will need to specify the name of checkboxes as:
<input type="checkbox" name="choice[]" />
and not not simply
<input type="checkbox" name="choice" />.
Now, for example, you have this in HTML:
<input type="checkbox" name="choice[]" value="choice1"> Choice1
<input type="checkbox" name="choice[]" value="choice2"> Choice2
<input type="checkbox" name="choice[]" value="choice3"> Choice3
Let's say, you tick the first and third checkbox,
In PHP, you can check the checkboxes checked as:
<?php
print_r($_POST['choice']);
?>
The output will be:
Array('0' => 'choice1',
'1' => 'choice3')
I hope this explains your doubt.
You will need to specify the name of checkboxes as an array:
then you get the values in array and then you can save in the database
you can mention the check boxes names differently such as 1,2,3,4,5,6.. and you post values using the form and get it as an array
for example
$values[0]=$_POST['1'];
$values[1]=$_POST['2'];
$values[2]=$_POST['3'];
$values[3]=$_POST['4'];
$values[4]=$_POST['5'];
$values[5]=$_POST['6'];
$values[6]=$_POST['7'];
$values[7]=$_POST['8'];
$values[8]=$_POST['9'];
$values[9]=$_POST['10'];
and then u can implode it to a variable and save it in the database
$skill_set = implode(",", $values);
You have to change your code to
name="choice[]"
To get more than one value from checkbox
You need to change the name of checkboxes to an array like this
<input type="checkbox" name="Choice[]" />
while reading the post value of check box read like this
$_POST['Choice'][0],$_POST['Choice'][1],...
Example
<input type="checkbox" name="Choice[]" value=" Checkbox 1"/> Checkbox 1<br>
<input type="checkbox" name="Choice[]" value=" Checkbox 2"/> Checkbox 2<br>
<input type="checkbox" name="Choice[]" value=" Checkbox 3"/> Checkbox 3<br>
If you had checked only checkbox 1 and 3 , then you can get values like this
$_POST['Choice'][0] => has the value of first checkbox that has been checked.
so $_POST['Choice'][0] will have value of Checkbox 1
$_POST['Choice'][1] => has the value of second checkbox that has been checked.
so $_POST['Choice'][1] will have value of Checkbox 3

PHP: How to get multiple checkbox values from database for same ID?

I am new to php & need little help here.
I've following code to INSERT multiple checkbox values into a table for same ID:
on my form I have:
<input type="checkbox" name="subcat[]" value="Mech">Mech
<input type="checkbox" name="subcat[]" value="Ele">Ele
<input type="checkbox" name="subcat[]" value="Civ">Civ
<input type="checkbox" name="subcat[]" value="Air">Air
<input type="checkbox" name="subcat[]" value="BSL">BSL
I've checked "Mech", "Ele" and "BSL"
and PHP to insert:
$subcat = $_POST['subcat'];
for($i=0; $i<sizeof($subcat);$i++){
$sql1="INSERT INTO mst_scatadd (party_code,scid)
VALUES ('$pcode',$subcat[$i])";
mysql_query($sql1,$con);
}
db looks something like...
sctid | party_code | scid
---------------------------------
1 | 01S001 | Mech
2 | 01S001 | Ele
3 | 01S001 | BSL
4 | 01K207 | Main
Now, how can I retrieve these values from db to my form for the same ID and make them as checked if I want to edit the checkboxes?
Little help would be appreciated!!
Thanks in adv.
EDIT 1:
Hello again guys!
I've done with inserting and retrieving checkbox values using implode and explode and its working fine.
Thanks to #Antoniossss for good suggession to keep checkboxes values as numbers(make sure the column in db should be VARCHAR)
Thanks to #Barmar to explain use of explode & thanks to #MarkTWebsite to share idea of if-else
Code for inserting multiple checkbox values:
foreach ($_POST['subcat'] as $_subcat)
{
$checksub[] = $_subcat;
} $finalsub = implode(',', $checksub);
$sql="INSERT INTO vendor_mst(party_code, subcat) VALUES ('$pcode','$finalsub')";
My final code to retrieve checkbox values from db...
sql="SELECT * FROM vendor_mst WHERE party_code like '".$searchname."'";
$result=mysql_query($sql,$con);
while ($row=mysql_fetch_array($result, MYSQL_BOTH)){
$checksub = explode(',',$row['subcat']);
}
if(in_array("1",$checksub))echo '<input type="checkbox" name="subcat[]" value="1" checked >Mech'; else echo '<input type="checkbox" name="subcat[]" value="1">Mech';
if(in_array("2",$checksub))echo '<input type="checkbox" name="subcat[]" value="2" checked >Ele'; else echo '<input type="checkbox" name="subcat[]" value="2">Ele';
if(in_array("3",$checksub))echo '<input type="checkbox" name="subcat[]" value="3" checked >Civ'; else echo '<input type="checkbox" name="subcat[]" value="3">Civ';
if(in_array("4",$checksub))echo '<input type="checkbox" name="subcat[]" value="4" checked >Air'; else echo '<input type="checkbox" name="subcat[]" value="4">Air';
if(in_array("5",$checksub))echo '<input type="checkbox" name="subcat[]" value="5" checked >BSL'; else echo '<input type="checkbox" name="subcat[]" value="5">BSL';
Thanks to stackoverflow!
I would rather go in direction of threating checkboxes as binary flags and store their binary OR operation into DB as integer. It is really easy to implement, and will simplify record relations in your database. To do that you need to change values of checkboxes into 2^n values. For example
<input type="checkbox" name="subcat[]" value="1">Mech
<input type="checkbox" name="subcat[]" value="2">Ele
<input type="checkbox" name="subcat[]" value="4">Civ
<input type="checkbox" name="subcat[]" value="8">Air
<input type="checkbox" name="subcat[]" value="16">BSL
selecting Mech and Civ should be storen in DB as 5 (binary 00101), Air+BSL would be 24 (11000b) and so on. To revert this process you would just simply test every bit of stored value and check/uncheck corresponding boxes in loop. I hope that you will get my point.
EDIT: example code as requested.
Be aware that I AM NOT a PHP programmer so there could (and definetly will be) syntax errors but I will do my best
To get user input you have to simply add values of checked boxes
$selected=0;
foreach($POST['subcat'] as $checkedBox){
$selected=$selected+$checkedBox
}
So now variable $selected will have encoded status of all checkboxes
To check which boxes (I never have troubles with that word) should be check or not you have to test every bit of stored value in DB. I dont know how are you generating your view, so i will provide only a template, you have to figure it out how to apply it to your project
$valueFromDb= /// some value fetched from DB
$maxValue= //// the highest value of your checkboxes, in my eg. 16
for($testValue=1;$testValue<=$limit;$testValue=$testValue << 1){
$result=($valueFromDb & $testValue) > 0;
// do something with checked result for current checkbox
}
variable result above will have checked status (boolean value) of coresponding checkboxes. Each loop iteration coresponds to different checkbox in order from Mech to BSL one by one.
Alternatively you can print checkboxes directly and set them as checked with if inscruction
$valueFromDb= // fetched value
<input type="checkbox" name="subcat[]" value="1" <?php if($valueFromDb & 1 >0) echo('checked') ?php>Mech
<input type="checkbox" name="subcat[]" value="2" <?php if($valueFromDb & 2 >0) echo('checked') ?php>>Ele
<input type="checkbox" name="subcat[]" value="4" <?php if($valueFromDb & 4 >0) echo('checked') ?php>>Civ
.... and so on and on and on
I have just noticed that combining those 2 methods would result in generating checboxes dynamicly in loop so the code will be much more readable. All you would need is to provide map of checbox value labels:)
I hope that eg. above will definetlly clearify how to apply such solution.
<?php
$checksub = array('1','2','3');
?>
<form action="<?php echo site_url('index/do_upload') ?>" method="post" enctype="multipart/form-data">
<label>Select file : <input type="file" name="userfile"></label>
<input type="submit" name="action">
<input type="checkbox" name="subcat[]" value="1" <?php if (in_array(1,$checksub)){ echo "checked"; }?>/>
</form>
You will need to use the PHP if statement;
I don't really understand your db structure, else I would provide code however, if you use PHP if, for each checkbox, check in the database to see if it's selected then;
if it is selected
echo '<input type="checkbox" name="subcat[]" value="Mech" selected>Mech';
else;
echo '<input type="checkbox" name="subcat[]" value="Mech">Mech';
Do you understand what I mean?
Source; HTML/CSS/PHP Developer for 3 years.
You can retrieve the subcats with:
SELECT party_code, GROUP_CONCAT(scid) scids
FROM mst_scadd
GROUP BY party_code
Then when you're fetching the rows from the database, you can do:
$scids = array_flip(explode(',', $row['scids']));
That will create an associative array whose keys are the subcategories. Then your code for displaying the checkboxes can be something like:
foreach ($all_subcats as $sc) {
echo '<input type="checkbox" name="subcat[]" value="' . $sc . '" ' .
(isset($scids[$sc]) ? 'checked' : '') . '>' . $sc;
}

Categories