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>
so i tried to get data from my database to checkbox and this is what i have tried :
<?php
$query = "SELECT * FROM siswa WHERE id_tingkatan='$idtingkatan'";
$result = $koneksi->query($query);
while($row=$result->fetch_assoc()){
?>
<input type="checkbox" name="murid[]" value="<?php echo $row['id_siswa']; ? >"><?php echo $row["nama_siswa"]; ?><br><br>
<?php } ?>
and save the value of checked checkbox into database, this is what i have tried :
if(isset($_POST["submit"]))
{
if(!empty ($_POST['murid']))
{
$i= 0;
foreach($_POST as $murid){
$kelas = $_POST['kelas'];
$murid = $_POST['murid'][$i];
$query = "INSERT INTO murid (id_kelas, id_siswa) VALUES ('$kelas', '$murid')";
$q = mysqli_query($koneksi, $query) or die (mysqli_error($koneksi));
$i++;
}
}
else
{
echo "<script type= 'text/javascript'>alert('Pilih minimal 1 siswa');</script>";
header('Location: ./kelas.php');
}
}
when i submit it does input to database but theres one extra row with id_siswa value as 0
The code inserts one record for each value in $_POST. However, $_POST contains all parameters sent (including submit), not just the checkbox array to be inserted. Iterate over the checkbox array $_POST['murid'] instead.
Change
foreach($_POST as $murid) ...
To
foreach($_POST['murid'] as $murid) ...
I have created a form that requires the user to input information on all fields and then submit the form. My goal is to get the user input and insert it into new records on the database. My current challenges are that since I used a for loop in PHP to create the table/form:
I can not access the input from $_POST
Not sure how to go about differentiating all of the rows and their inputs from each other (since I used a loop to create them). I was thinking an array...
Please see a screenshot of the form I am working with.
Below is what I have for my submit button.
if (isset($_POST['submit'])) {
$date = date('m\/d\/Y');
$ordnum = $_POST['cpOrderNumber'];
$ponum = $_POST['cpPoNumber'] . $_POST['cpPoNumberF'];
$palnum = $_POST['palnum'];
$casecount = $_POST['casecount'];
$cpsflot = $_POST['cpsflot'];
$sscc = $_POST['sscc'];
if(!empty($_POST['cpOrderNumber']) || !empty($_POST['cpPoNumber'])) {
require_once('mydatabase.php');
$query = "INSERT INTO ASN (date, ordnum, ponum, palnum, casecount, cpsflot, sscc )
VALUES ('$date', '$ordnum', '$ponum', '$palnum', '$casecount', '$cpsflot', '$sscc')";
$insert = sqlsrv_query($dbc, $query);
if( $insert === false ) {
die('Could not connect to database');
}
}
else {
die('Please enter the appropriate information');
}
sqlsrv_close($dbc);
}
And here is where I am having difficulty. I can get $date, $ordnum, and $ponum to insert into the database however $palnum will not. As you can see from what I've commented out I have tried to use an array.
<?php
for ($x = 1; $x < 25; $x++) {
echo
'<tr id="' .$x. '">
<td style="font-size: 160%" name="palnum" id="pallet">' .$x. '</td>
<td id="caseCount"><input type="number" name="casecount" id="inputText_Small" maxlength="2"/></td>
<td id="hilltopLot"><input type="text" name="cpsflot" id="inputText_Order" value="" maxlength="10"/></td>
<td id="sscc"><input type="number" name="sscc" id="inputText_Medd" value="" maxlength="4"/></td>
</tr>';
$palnum[$x] = $x;
//$palnum[$x] = 'palnum'.$x;
//$palnum = $palnumx.$x;
//$palnum1 = $palnum[1];
}
//echo count($palnumx);
//echo $palnum[1];
?>
i think you are looking for this. not 100% though. Basically, you can name an input wityh brackets to make it behave like an array in the post.
<input name="recurringName[]" value="moo" />
<input name="recurringName[]" value="moo2" />
if you do that, in the post you can access data this way
$_POST['recurringName'][0] == 'moo'
$_POST['recurringName'][1] == 'moo2'
i hope this helps! let me know if i did not understand you clearly
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.