Information not updating to database after deselecting a checkbox - php
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>
Related
PHP Checkbox Form Validation with SQL
I have mySQL table containing rows of user reviews of films. All columns a are functional except for the 'liked' column. The 'liked' column is a boolean value. This The table must be displayed on my website, converting the boolean to a 'yes' or 'no'. Here is the code for the table: while($review = $reviews->fetch_object("Review")) { $liked = $review->liked; $convert = ($liked) ? 'yes' : 'no' ; echo "<tr> <td>{$review->reviewer} </td> "; echo "<td>{$review->comment} </td>"; echo "<td> $convert </td></tr>"; As you can see the conversion is functional. The page also contains a form where users can submit their reviews. Using a checkbox, users 'check' if they like the film, or don't check if they don't. <div class="form-group"> <label for="liked" class="col-xs-2 c">Did you like this film?:</label> <div class="col-xs-10"> <input name="liked" type="checkbox" value="1" > Tick yes if you did </div> </div> In a seperate PHP file; 'Process-review', I use an INSERT query to insert new rows into the table. if(isset($_POST['name']) && isset($_POST['comment']) && isset($_POST['film_id'])) { $reviewer = $_POST['name']; $comment = $_POST['comment']; $film_id = $_POST['film_id']; if(isset($_POST['liked'])) { $liked = $_POST['1']; } else { $liked = $_POST['0']; } $db->query("INSERT INTO review (film_id, reviewer, liked, comment) VALUES('$film_id', '$reviewer', '$liked', '$comment')"); header('Location: show-film.php?id='.$film_id); } else{ $name = null; echo "no name supplied"; } All other fields work except for the 'liked' field. As you can see I have tried using an if statement within the initial if statement to return a '1' if the checkbox is ticked and '0' if the checkbox isn't ticked. Yet when I check the box, the table still returns a 'no'. Even if i change the $convert so both values are 'yes' it still returns no which begs the question where is it getting the 'no' from. Here is an image of the table to give you a visual representation of what I'm working with here
You're trying to insert values that don't exist. Replace your if condition with: if(isset($_POST['liked']) && $_POST['liked'] == 1) { $liked = 1; } else { $liked = 0; } Aside from that, you're opening yourself up to an injection attack. You should use prepared statements. At the very least run every variable you're passing to the database through mysqli_real_escape_string.
updating checkbox value to database
im trying to update checkbox value into database. i already write some code and it worked updating the database..however for some reason i got undefined index in my combobox variable..here is my code.. code to display existing data into checkbox <tr> <td><label for="cbPin">Pin this post</label></td> <td><input type="checkbox" name="cbPin" class="checkbox checkbox-warning" id="cbPin" <?php if ($pin == 0) { ?> value="0" <?php } else { ?> checked value="1" <?php } ?> /></td> </tr> this one is variable to render the form $pin = $row[9]; and this one if button submit clicked $pin = ($_POST['cbPin']); if ($pin == '') { $pinpost = 0; } else { $pinpost = 1; } and this is my query if ($stmt = $mysqli->prepare("UPDATE tblanouncement SET title = ?, message = ?, pinpost = ? WHERE anouncementId=?")) { $stmt->bind_param("ssii",$title, $message, $pinpost, $id); $stmt->execute(); $stmt->close();
A checked checkbox sends its name and value. A non-checked checkbox is not a successful control and won't be submitted at all. If you aren't dealing with multiple checkboxes of the same name, use isset to see if the data exists or not. Don't assume you will have a value for it in the POST data array.
Inserting checkbox value of 0 or 1 to database 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">
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"/>