Inserting checkbox value of 0 or 1 to database PHP - php

I placed a new checkbox on an existing form on this website I am working on and I want it to update the database with a 0 or 1 based on if the checkbox has a check or not. I have been at this for some hours now to no avail.
Here is my input code:
<input type="hidden" name="propHosp" value="0">
<input type="checkbox" name="propHosp" <? if($propHosp == "1") echo "checked='checked'"; ?> value="1">
Here is the code I placed around the SQL Insert query code:
$hospValue = (isset($_GET['propHosp'])) ? intval($_GET['propHosp']) : 0; // returns 0 or 1
$sql = "INSERT INTO comments SET ";
$sql.= "propHosp = $hospValue";
--other sql lines omitted--
propHosp is the column and its default is 0. It should be a 1 if the checkbox is checked. It just keeps creating the new row with a 0 every time. I have tried changing $_GET to $_POST as well, no luck. Thanks for your help!

if(isset($_POST['propHosp']))
{
$hospValue = 1;
}
else
{
$hospValue = 0;
}
Only one input as well, <input type="checkbox" name="propHosp">

Related

Information not updating to database after deselecting a checkbox

I am having issues when I untick a checkbox and leave it blank and update my PHP / MySQL form, the data is not saved in the database. Updates text / date fields are working fine.
Code
$learning_opportunities = isset($_POST['learning_opportunities']) ? $_POST['learning_opportunities'] : $contact['learning_opportunities'];
$stmt = $pdo->prepare('UPDATE contacts SET current_living_situation=?, personal_strengths=?, skills_training=?, currently_spend_time=?,personal_goals=?,housing_situation_transport_childcare=?,
learning_actual_end_date=?, partcipant_complete_course=?, withdrawal_reason=?,participant_intended_learning=?,pcp_education=?,
coursestart_date=?,education_provider_name=?,course_title=?,course_level=?,planned_glh=?,in_paid_employment=?,in_paid_employment_start_date=?,
in_paid_employer_name_address=?,in_paid_job_title=?,in_paid_contracted_hour=?,not_in_paid_employment=?,pcp_gap_year=?,
pcp_others=?,pcp_voluntary_work=?,destination_progression_date=?,destination_progression_collection_date=?,project_officer_name=?,
project_officer_signature=?,project_officer_date=?,participant__name=?,participant__signature=?,participant__date=?,
final_assessment_progress_you_made=?,final_assessment_progress_your_goal=?,final_assessment_progress_your_reach_goal=?,
final_assessment_progress_overall=?,final_assessment_participat_name=?,final_assessment_participat_signature=?,
final_assessment_participat_date=?,final_assessment_project_worker_name=?,final_assessment_project_worker_signature=?,
final_assessment_project_worker_date=?,learning_opportunities=?,contact_for_other_purposes=?,empowering_communities=?,empowering_communities_name=?,empowering_communities_sign=?,empowering_communities_date=?,
participant_enrolled_onto=?,participant_moved_another_provider=?,participant_eligible_free_school=?,british_passport=?,
eec_passport=?,euss_via_home=?,preferred_evidence=?,provide_preferred_evidence=?,option_adoption_vertificate=?,option_driving_licence=?,
option_non_eu_passport=?,option_biometric_immigration=?,option_current_immigration=?,option_marriage_civil_partnership=?,
option_other_evidence=?,option_nine=?,details_evidence_provided=?,dwp_job_centre_letter=?,confirmation_relevant_organisation=?,self_certification_evidence=?,
partcipant_told_support=?,participant_file_completed_remotly=?,declaration_name_please_print=?,declaration_job_title=?,declaration_organisation=?,
declaration_signature_date=?,declaration_signature=? where id = ?');
$result = $stmt->execute([$current_living_situation,$personal_strengths,$skills_training,$currently_spend_time,$personal_goals,
$housing_situation_transport_childcare,$learning_actual_end_date,$partcipant_complete_course,$withdrawal_reason,$participant_intended_learning,$pcp_education,
$coursestart_date,$education_provider_name,$course_title,$course_level,$planned_glh,$in_paid_employment,$in_paid_employment_start_date,
$in_paid_employer_name_address,$in_paid_job_title,$in_paid_contracted_hour,$not_in_paid_employment,$pcp_gap_year,$pcp_others,
$pcp_voluntary_work,$destination_progression_date,$destination_progression_collection_date,$project_officer_name,$project_officer_signature,
$project_officer_date,$participant__name,$participant__signature,$participant__date,$final_assessment_progress_you_made,
$final_assessment_progress_your_goal,$final_assessment_progress_your_reach_goal,$final_assessment_progress_overall,$final_assessment_participat_name,
$final_assessment_participat_signature,$final_assessment_participat_date,$final_assessment_project_worker_name,$final_assessment_project_worker_signature,
$final_assessment_project_worker_date,$learning_opportunities,$contact_for_other_purposes,$empowering_communities,$empowering_communities_name,$empowering_communities_sign,$empowering_communities_date,
$participant_enrolled_onto,$participant_moved_another_provider,$participant_eligible_free_school,$british_passport,
$eec_passport,$euss_via_home,$preferred_evidence,$provide_preferred_evidence,$option_adoption_vertificate,$option_driving_licence,
$option_non_eu_passport,$option_biometric_immigration,$option_current_immigration,$option_marriage_civil_partnership,$option_other_evidence,$option_nine,
$details_evidence_provided,$dwp_job_centre_letter,$confirmation_relevant_organisation,$self_certification_evidence,$partcipant_told_support,
$participant_file_completed_remotly,$declaration_name_please_print,$declaration_job_title,$declaration_organisation,$declaration_signature_date,
$declaration_signature, $_POST['id']]);
if($result == true){
$details = "<b>All Data Updated</b>";
// Insert new record into the contacts table
$stmt = $pdo->prepare('INSERT IGNORE INTO client_activity (id,client_id,date,time,details,username) VALUES (?,?,?,?,?,?)');
$client_activity = $stmt->execute([ null,$_POST['id'],date("Y/m/d"),date("H:i:s"),$details,$_SESSION['name'] ]);
if($client_activity == true){
$msg = 'Updated Successfully!';
Form code
<input type="checkbox" name="learning_opportunities" value="learning_opportunities" <?php if($contact['learning_opportunities']=="Yes"){ echo 'checked'; } ?>> About courses or learning opportunities.<br>
I have read countless articles and tutorials and can't get it to update the data.
The assignment of the variable $learning_opportunities does not make any sense at all.
Only checked checkboxes are sent to the server.
The following snippet will just force the checkbox to be set back to true if the old value $contact['learning_opportunities'] was already true, making it impossible to uncheck the checkbox
$learning_opportunities = isset($_POST['learning_opportunities']) ? $_POST['learning_opportunities'] : $contact['learning_opportunities'];
If you want to be able to update that field you just need this assignment:
$learning_opportunities = isset($_POST['learning_opportunities']) ? 1 : 0;
After sending the form with the checkboxes keep in mind, that there are 2 scenarios possible:
if you checkbox was checked you will get "on" in $_POST['learning_opportunities'].
if your checkbox wasn't checked you will not get 'learning_opportunities' index in the $_POST array at all
Check this demo:
index.php
<?php
$contact['learning_opportunities'] = isset($_POST['learning_opportunities']) ? "yes" : "no";
?>
<form action="index.php" method="POST">
<input type="checkbox" name="learning_opportunities" <?= $contact['learning_opportunities'] === "yes" ? 'checked' : "" ?>>
About courses or learning opportunities.
<br>
<input type="submit" value="Submit">
</form>

Checkbox to be selected according to database value

I need some help !, I am working on a project where I want to select all those check boxes, which has value fetched from database. Let suppose I have a table which has 4 fields as id, news_title, news_desc and flag. flag field has value like 0 for not checked and 1 for checked. now when I query that table I want only those check boxes which has flag value 1 should be checked and other are not not checked.. How can I do this.. Please Help. Thanks.
Assuming you know how to get the result from mysql you would put the following into your while results loop.
if ($row['flag'] == 1){
echo '<input name="checkbox_name" id="checkbox_id" type="checkbox" checked="yes">';
}else{
echo '<input name="checkbox_name" id="checkbox_id" type="checkbox">';
}
obviously this is just for illustration - there are better ways to do this (like storing $checked = "" or $checked = 'checked="yes"' and the echoing it in-line).
in the HTML it can be checked="yes" or checked
Assuming $row contains your result row, you could use something like:
echo '<input type="checkbox" name="name"' . ($row['flag']==1?'selected="selected"':null) . '/>';

retrieve 1 or more checkbox value from database

this is my html code
<input type='checkbox' name='cbox[]' value='Jaywalking' />
Jaywalking<br>
<input type='checkbox' name='cbox[]' value='Littering' />
Littering<br>
<input type='checkbox' name='cbox[]' value='Illegal Vendor' />
Illegal Vendor
this is my php code
if(isset($_POST['save']))
{
$license_save=$_POST['license'];
$stickerno_save=$_POST['stickerno'];
$fname_save=$_POST['fname'];
$mname_save=$_POST['mname'];
$lname_save=$_POST['lname'];
$no_save=$_POST['no'];
$street_save=$_POST['street'];
$city_save=$_POST['city'];
$bdate_save=$_POST['bdate'];
$violationplace_save=$_POST['violationplace'];
$dd_save=$_POST['dd'];
$mm_save=$_POST['mm'];
$yy_save=$_POST['yy'];
$hh_save=$_POST['hh'];
$min_save=$_POST['min'];
$ampm_save=$_POST['ampm'];
if(is_array($_POST['cbox'])) $violation_save=implode(',',$_POST['cbox']); else $violation_save=$_POST['cbox'];
mysql_query("UPDATE tblcitizen SET license ='$license_save', stickerno ='$stickerno_save', fname ='$fname_save', mname ='$mname_save', lname ='$lname_save', no ='$no_save', street ='$street_save', city ='$city_save', bdate ='$bdate_save', violationplace ='$violationplace_save', dd ='$dd_save', mm ='$mm_save', yy ='$yy_save', hh ='$hh_save', min ='$min_save', ampm ='$ampm_save', violation ='$violation_save', type ='$type_save', officer ='$officer_save', date ='$date_save', ttime ='$ttime_save' WHERE id = '$id'")
or die(mysql_error());
echo "<script>alert('Successfully Edited')</script>";
header("Location: citizen.php");
}
I want to edit some account registered, how can i retrieve 1 or more checkboxes value from the database.
EDITED FOR BETTER ANSWER
if(is_array($_POST['cbox'])) $violation_save=implode(',',$_POST['cbox']); else $violation_save=$_POST['cbox'];
Your query is taking the cbox array, turning it into a string with commas if it is an array (if more than one checkbox was checked), otherwise inserting just one checkbox value with no comma.
To get the values out, just read the string, then compare it with a php strpos()
<?
// Get the checkboxes that were previously selected
$result = mysql_query("SELECT violation FROM tblcitizen WHERE id = '$id'") or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
// put the string into a variable
$mystring = $row['violation'];
}
// use a ternary to determine if this checkbox exists
// if so, make the variable $checked to check the checkbox, otherwise leave it blank
$checked = (strpos($mystring, 'Jaywalking')) ? 'checked' : '';
?>
// write the checkbox to the page. and echo the contents of $checked
// if it was found with strpos() then it will be checked, otherwise it will not be
// <?= ?> is a quick way to echo a variable without the echo command
<input type='checkbox' name='cbox[]' value='Jaywalking' <?=$checked;?> />
I don't quite understand your sentence of "how can i retrieve 1 or more check boxes value from the database" but since I can see your update statement, I am assuming that you want to take the one or more value from the check boxes and update the table in the database.
You will receive the check box value in form of an array
You need to loop through the array and get the value
Store value in one variable and you are good to go to store it in the database
foreach ($cbox as $val) {
$Violation .= $val.",";
}
You can always remove the last comma using PHP substring by the way. Cheers, hope this helps you and anybody out there. Thank You.

How to work with checkboxes in relation to database?

Hi I am trying to build a form with checkboxes and upon submitting the form, I want to see which checkboxes were checked and update the database accordingly. How is this done? I've tried so many different code and none of them worked. The closest I've gotten was to update only the checked ones. I also need to update the database if they are unchecked as well like a toggle.
So far my code is like this for the form
<form action="" method="post">
<input type=checkbox" value="<?php echo member['id']; ?>" name="member[]" />
<input type="submit" name="update" value="Update" />
</form>
And for the PHP loop I have (excerpt)
foreach ((array)$_POST['test'] as $member) :
$sql = "UPDATE `sp_members` SET `allow_test` = '1' WHERE `id` = '$member'";
Since I think the loop only picks up the checkboxes that are checked, it doesn't pick up the ones that were orignally checked and now unchecked...
Any help appreciated!
Simply update everything instead of trying to figure out what changed - if you programmed it yourself, you would have to make your code a lot more complicated, and as the database is already optimized for speed, it's better to just stuff it in the DB and let it handle it.
You could use a ternary operator to set the correct value.
$sql = "UPDATE `sp_members` SET `allow_test` = '"
. ( $_REQUEST['checkbox'] ? 1 : 0 )
. "' WHERE `id` = '" . mysql_real_escape_string( $member ) . "'";
It checks $_REQUEST['checkbox'] for a non-null, non-zero string and if true, returns 1, if false, returns 0.
(($_post['member']) ?$allow_test = 1 : $allow_test = 0;
$sql = "UPDATE `sp_members` SET `allow_test` = $allow_test WHERE `id` = '$member'";
The reason why this hasn't been working (and won't in the already provided answers) is because checkboxes that are not checked won't exist in the $_POST/$_REQUEST arrays. The other side of that is if they do exist, they must be true.
When you're doing the check to see what the value is, you are causing an error because the key to the array doesn't exist.
Instead, you need to know the available checkboxes and then check if each isset() in the array.
Webform:
<form action="foo.php" method="post">
<input type="checkbox" value="<?php echo $value1; ?>" name="checkbox1" />
<input type="checkbox" value="<?php echo $value2; ?>" name="checkbox2" />
<input type="submit" name="update" value="Update" />
</form>
PHP:
$checkboxes = array(
'column1' => 'checkbox1',
'column2' => 'checkbox2',
);
foreach ($checkboxes as $column => $checkbox)
{
$value = (isset($_POST[$checkbox]) ? 1 : 0);
$sql = "UPDATE `table` SET `$column` = '$value' WHERE `id` = '$member'";
}
When confronted with this, I usually punt and rely on a transaction to update this stuff for me. As you've discovered, unchecked checkboxes won't get submitted with the form, so you'd have to do tedious comparisons to figure out what's changed each time and build up an appropriate update and/or delete query sequence.
Instead, I fire up a transaction, delete all the old checkbox values stored in the DB, and then insert the new ones submitted with this request. Unless you've got the checkboxes acting as foreign keys and/or triggers set on them at the DB level, this is a relatively lightweight option and saves you the trouble of having to compare the old and new lists for changes.

php form issues

I have a form with which I am trying to display a form with checkboxes, and then insert into a database whether or not those checkboxes are checked. Then, each time the page is called, check the value and append information to the html form to appropriate display the checkbox as checked or not.
I have modified the below code example to make it short, and I am aware that I am assigning the checked value to 'value', which won't do anything.
The approach of
<input type="checkbox" name="notice" value="checked" checked/>
to display a checkbox as checked, while not valid html, works in every browser, and is based on the example here. I would prefer to stick with this approach.
Now, I don't see what is wrong with my code.
The first steps should be to retrieve the values from the database, of which onyl one row will be retrieved, as article_no is a primary key. If nothing is retrieved, then the variables are simply assigned "", which results in the checkbox being unchecked.
As the value is checked, if it is selected, this should be inserted into the database, and will show as checked upon next viewing of the page.
Now, as it is, this code compeltely fails. firebug does not show anything being sent or received in the console, no erros are recorded either with php or mysql, nothing appears in the database despite the fields and such being correct, no mysql errors are reported...
What is the problem?
The code:
<?php
error_reporting(E_ALL);
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"];
else
if (isset($_POST["cmd"]))
$cmd = $_POST["cmd"];
if (isset($_GET["pk"]))
{ $pk = $_GET["pk"];}
if (isset($_POST["deleted"]))
{ $deleted = $_POST["deleted"];}
if (isset($_POST["notice"]))
{ $notice = $_POST["notice"];}
$con = mysqli_connect("localhost","user","pass", "db");
if (!$con) {
echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error();
exit;
}
$con->set_charset("utf8");
$getformdata = $con->query("select * from TEST where ARTICLE_NO = '$pk'");
$checkDeleted = "";
$checkNotice = "";
while ($row = mysqli_fetch_assoc($getformdata))
{
$checkDeleted = $row['deleted'];
$checkNotice = $row['notice'];
}
if($cmd=="submitinfo"){
$statusQuery = "INSERT INTO TEST VALUES (?, ?, ?)";
if ($statusInfo = $con->prepare($statusQuery)) {
$statusInfo->bind_param("sss", $pk, $deleted, $notice);
$statusInfo->execute();
$statusInfo->close();
} else {
print_r($con->error);
}
}
echo "<form name=\"statusForm\" action=\"x.php\" method=\"post\" enctype=\"multipart/form-data\">
<h1>Editing information for auction: ".$pk."</h1>
Löschung Ebay:
<input type=\"checkbox\" name=\"deleted\" value=\"checked\" ".$checkDeleted." align=\"right\"/>
<br />
Abmahnung:
<input type=\"checkbox\" name=\"notice\" value=\"checked\" ".$checkNotice." align=\"left\"/>
<br />
<input type=\"hidden\" name=\"cmd\" value=\"submitinfo\" />
<input name=\"Submit\" type=\"submit\" value=\"submit\" />
</form>";
In the actual form/page, I have appropriate sanitization in place.
A big problem is that nothing is being inserted into the database and no errors are being returned at all!
It's important to remember that unchecked checkbox does not contribute any values to a form when it is sent. When the deleted box is unchecked, there is no $_POST['deleted'] value set.
With that in mind, it looks like you don't actually set the value of $deleted if the checkbox is cleared. Use an idiom like this.
$deleted = isset($_POST["deleted"]) ? 1: 0;
Substitute the 1 and 0 with whatever values you want in your database table for the checked and unchecked states (in your case, "checked" and "")
Along the same lines as Paul Dixon's answer, I've done this at times:
<input type="hidden" name="notice" value="not checked" />
<input type="checkbox" name="notice" value="checked" checked="checked" />
If the user unchecks the checkbox, the hidden input's value gets sent instead. This way, $_POST['notice'] is always sent to your script.
I thought checkboxes should be done this way:
<input type="checkbox" name="notice1" value="value1" checked="checked"/>
<input type="checkbox" name="notice2" value="value2" checked="checked"/>

Categories