Checked a checkbox on page refresh - php

I'm trying to keep a checkbox checked, but after I refresh the page, database is update with satus '1' but on front-end checkboxes is unchecked, hope somebody can help.
Here is my code
<td>
<span>
<input type='checkbox' name='Id' value='".$checkSubRow['Checklist_Id']."' class='check' id='Completed-".$checkSubRow['Checklist_Id']."' onClick='Completed(".$checkSubRow['Checklist_Id'].")'
/>
echo (isset($_POST['checkbox']))? "checked='checked'": "";
</span>
</td>

the name=Id is what you will need to check. So change the $_POST['checkbox'] to $_POST['Id']

I think there one issue that the echo (isset($_POST['checkbox']))? "checked='checked'": ""; is not inside the input tag. So, it wont apply to the tag. Also, the name should be used in the $_POST['checkbox'] like $_POST['Id']
e.g.
<td>
<span>
<input type='checkbox' name='Id' value='".$checkSubRow['Checklist_Id']."' class='check' id='Completed-".$checkSubRow['Checklist_Id']."' onClick='Completed(".$checkSubRow['Checklist_Id'].")' <php echo (isset($_POST['Id']))? "checked='checked'": ""; ?>/>
</span>
</td>
Try it out.

I didn't find solution for that so i changed it littile bit. here is revised code.
while ($checkSubRow = $checkSub->fetch(PDO::FETCH_ASSOC))
{
if($checkSubRow['Status'])
{
$checked = "checked";
}
else
{
$checked = "";
}
echo "<tr>
<td>
<span><input type='checkbox' name='Id' class='check' id='Completed-".$checkSubRow['Checklist_Id']."' $checked onClick='Completed(".$checkSubRow['Checklist_Id'].")' /></span>
</td>

Related

checkbox could not uncheck php

I have written a code to save the check values of checkboxes to database.
check condition is working fine as in the checked values are saving to database when submit and it keeps checked when submit and refresh.
But when it uncheck and submit then refresh the page the checkbox still keeps remained checked. It won't saved the status of unchecked.
I include a chunk code which is related to this issue. If anyone can get the issue that'd be great.
echo "<form action='' class='' method='post'><tr>";
$sql_stamp = "SELECT check_list FROM time_stamps WHERE nJobNumber=".$nJobNumber;
$query_stamp = $conn->prepare($sql_stamp);
$query_stamp->execute();
$numRows = $query_stamp->rowCount();
if($numRows > 0){
$row_stamp = $query_stamp->fetch(PDO::FETCH_ASSOC);
$checkboxes = explode(',',$row_stamp['check_list']);
echo ' <td><center> <input type="checkbox" name="check_list[]" value="shop_drawing" '.(in_array( "shop_drawing",$checkboxes) ? "checked=checked" : "").'></td>';
echo ' <td><center><input type="checkbox" name="check_list[]" value="site_measure" '.(in_array( "site_measure",$checkboxes) ? "checked=checked" : "").'></td>';
echo ' <td><center><input type="checkbox" name="check_list[]" value="shop_drawings_approved" '.(in_array( "shop_drawings_approved",$checkboxes) ? "checked =checked" : "").'></td>';
echo '<td><center> <input type="checkbox" name="check_list[]" id="check" value="batch" '.(in_array( "batch",$checkboxes) ? "checked=checked" : "").'></td>';
echo '<td><center> <input type="text" name="batch_no"><br> </td>';
echo ' <td><center> <input type="submit" name="submit" value="Submit"/> </td>';
echo '<td><input type="hidden" name="job_number[result]" value="'."true".'"</td>';
echo '<td><input type="hidden" name="job_number[number]" value="'.$nJobNumber.'"</td>';
}else{
echo '<td><center><input type="checkbox" name="check_list[]" id="check" value="shop_drawing"></td>';
echo '<td><center><input type="checkbox" name="check_list[]" id="check" value="site_measure"></td>';
echo '<td><center><input type="checkbox" name="check_list[]" id="check" value="shop_drawings_approved"> </td>';
echo '<td><center> <input type="checkbox" name="check_list[]" id="check" value="batch"></td>';
echo '<td><center> <input type="text" name="batch_no"><br> </td>';
echo "<td><center> <input type='submit' name='submit' value='submit'></td>";
echo '<td><input type="hidden" name="job_number[result]" value="'."false".'"</td>';
echo '<td><input type="hidden" name="job_number[number]" value="'.$nJobNumber.'"</td>';
}
echo "</tr> </form>";
}
echo "</tbody> </table>";
?>
Insert values to database:
if(isset($_POST['submit']))
{
$checkbox = $_POST["check_list"];
$job_number = $_POST["job_number"];
$batch_no = $_POST["batch_no"];
date_default_timezone_set('Australia');
$date_time = date("Y-m-d h:i:sa");
//$username = "$SESSION[userid]";
if($job_number["result"] == "true"){
if(!empty($_POST['check_list']))
{
$checkboxes = implode(",",$_POST['check_list']);
$stmt = $link->prepare('UPDATE time_stamps SET time_date=?,username=?, batch_no=?,check_list=? WHERE nJobNumber=?');
$stmt->bind_param('ssssi',$date_time,$username,$batch_no,$checkboxes,$job_number["number"]);
$stmt->execute();
}
}
else{
if(!empty($_POST['check_list']))
{
$checkboxes = implode(",",$_POST['check_list']);
$stmt = $link->prepare('INSERT INTO time_stamps (nJobNumber,time_date,username,batch_no,check_list) VALUES (?,?,?,?,?)');
$stmt->bind_param('issss',$job_number["number"],$date_time,$username,$batch_no,$checkboxes);
$stmt->execute();
}
}
}
Basically, What's my requirement is when a user uncheck a 'checked' checkbox it should be unchecked when submit the form (after a refresh). But in my case it keeps checked.
Neither of your queries will execute if the user submits a form with no checkboxes checked. While this may be ok for your INSERT query, it will not allow the check_list field to be updated. So you will need to change the code for updates from this:
if(!empty($_POST['check_list'])) {
$checkboxes = implode(",",$_POST['check_list']);
$stmt = $link->prepare('UPDATE time_stamps SET time_date=?,username=?, batch_no=?,check_list=? WHERE nJobNumber=?');
$stmt->bind_param('ssssi',$date_time,$username,$batch_no,$checkboxes,$job_number["number"]);
$stmt->execute();
}
to this:
$checkboxes = empty($_POST['check_list']) ? '' : implode(",",$_POST['check_list']);
$stmt = $link->prepare('UPDATE time_stamps SET time_date=?,username=?, batch_no=?,check_list=? WHERE nJobNumber=?');
$stmt->bind_param('ssssi',$date_time,$username,$batch_no,$checkboxes,$job_number["number"]);
$stmt->execute();
You may also want to change the insert code in the same way if you want to insert a record even when the user doesn't check any checkboxes.
Thanks to #Phil for his input.
I think I see a couple of problems. I see this line:
$job_number = $_POST["job_number"];
But then I see you use this:
if($job_number["result"] == "true"){
So I ask, is $job_number an array or just a string/value?
Also, unchecked checkboxes don't submit a value. And since you test for a not empty $_POST['check_list'] value your UPDATE will never run. Remove the ! character.

Send values to db when multiple checkboxes are checked

I am loading some data from a db table to checkboxes. When a user checks boxes and submits, the values from these checkboxes need to be added to a different table. With the code I have now, I am able to send values of one checked box. What am I missing in sending the values of all the checked checkboxes?
<table>
<?php
$q5=mysqli_query($link,"SELECT * FROM brands_offer WHERE Brand_Id='$bid' AND Published='1' ");
while($row5 = mysqli_fetch_array($q5)){
$catid= $row5['Catg_Id'];
$subcatid= $row5['Subcatg_Id'];
$pid= $row5['Product_Id'];
?><tr><td>
<form action="store-admin.php?search=<?php echo $stname;?>#stock" method="post">
<input type="checkbox" name="checkbox" value="<?php echo "$bname,$catid,$subcatid,$pid";?>" >
<?php
echo $bname;
echo " -> ";
echo $catid;
echo ", ";
echo $subcatid;
echo ", ";
echo $pid;
echo " ";
}
?></td></tr>
<input type="submit" value="Save Changes" name="add" >
</form>
</table>
<?php
if(isset($_POST['add']))
{
$chk = $_POST['checkbox'];
$val = explode(",",$chk);
$bn = $val[0];
$cid= $val[1];
$scid= $val[2];
$prid= $val[3];
echo "<script type='text/javascript'>alert('brand: ". $bn."')</script>";
echo "<script type='text/javascript'>alert('cat: ". $cid."')</script>";
echo "<script type='text/javascript'>alert('sub: ". $scid."')</script>";
echo "<script type='text/javascript'>alert('pr: ". $prid."')</script>";
}?>
Use brackets in your checkbox name attribute name="checkbox[]" and your post variable will be an array of selected values.
Edit: I noticed you have form opening tag inside the while loop. You need to put it before while loop otherwise its generating tons of opening form tags.
So it looks like you have only one checkbox. If you want to POST the values of all the checkboxes as an array I believe you need to add [] to the name of your input field. So:
<input type="checkbox" name="checkbox[]" value="<?php echo "$bname";?>"/>
<input type="checkbox" name="checkbox[]" value="<?php echo "$catid";?>"/>
<input type="checkbox" name="checkbox[]" value="<?php echo "$subcatid";?>"/>
<input type="checkbox" name="checkbox[]" value="<?php echo "$pid";?>"/>
Hopefully I understood your question.

Checkboxes are checking out

I've got a page with checkboxes generated with the database. When we press the checkbox and submit it, it is working fine and it is updating in the database. But when I try to uncheck "1" checkbox it is checking out all checkboxes which are selected.
Query:
if(isset($_POST['submit'])){
foreach ($_POST['untrain'] as $room_id => $user_id) {
// This query needs protection from SQL Injection!
$user_id;
$untrainQuery = "UPDATE room_users SET trained = '1' WHERE user_id = $user_id AND room_id = $room_id";
$db->update($untrainQuery);
}
}
if(isset($_POST['submit'])){
foreach ($_POST['amk'] as $room_id => $user_id) {
// This query needs protection from SQL Injection!
$user_id;
$untrainedQuery = "UPDATE room_users SET trained = '0' WHERE user_id = $user_id AND room_id = $room_id";
$db->update($untrainedQuery);
}
}
Checkboxes:
<?php
if($room->trained == 1)
{ ?>
<input type='hidden' value="<?php echo $room->user_id; ?>" name="amk[<?php echo $room->room_id; ?>]">
<input type='checkbox' value="<?php echo $room->user_id; ?>" name="trained[<?php echo $room->room_id; ?>]" checked>
<?php echo "Y"; }
else{ ?>
<input type='checkbox' value="<?php echo $room->user_id; ?>" name="untrain[<?php echo $room->room_id; ?>]">
<?php echo "N";
}?>
</td>
<Td><?php
if($room->active == 1) {
?> <input type='checkbox' name="<?php echo $room->room_id; ?>" checked>
<?php echo "Active"; }
else { ?>
<input type='checkbox' name="<?php echo $room->room_id; ?>"
<?php echo "Inactive"; } ?>
I used the trick with the "hidden" input before the checkbox, but the only problem is that it is not working. When I click on it, it resets all checkboxes to 0.
I think you are missing how the combo checkbox + hidden input does work.
So here you go freely inspired by this answer:
<input id="foo" name="foo" type="checkbox" value="1" />
<input name="foo" type="hidden" value="0" />
Looks like you do know, if you use the trick, that, if the checkbox is unchecked, it will not be present in the post. So to trick the form, we will always add an hidden field. And if the checkbox is checked, then the fact that it will be included in the post is going to override the value of the hidden input.
So for your specific problem :
<td>
<input type="checkbox" value="1" name="trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>]" <?php echo ($room->trained == 1) ? ' checked' : '' ?> /> Trained
<input type="hidden" value="0" name="trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>]"/>
</td>
Please note the use of the ternary operator on this part of the code <?php echo ($room->trained == 1) ? ' checked' : '' ?> which I may use a lot when writing html template.
Please also note the trick on the name trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>] which is needed because we cannot set the user_id as value of the input.
Then for the processing part :
if ( isset ( $_POST['submit'] ) ) {
foreach ( $_POST['trained'] as $ids => $value ) {
// This query needs protection from SQL Injection!
// ^ good point, on which I would suggest you using PDO and prepared statement :)
list($room_id,$user_id) = explode('_',$ids);
// ^ now need to explode the name on the underscore to get both user_id and room_id cf the trick above
$untrainQuery = "UPDATE room_users SET trained = '$value' WHERE user_id = $user_id AND room_id = $room_id";
$db->update ( $untrainQuery );
}
}
Wash, rinse, repeat for every checkbox you need and you should be good to go.

How to save checkbox status after form is submitted

I have a PHP code to display table data with a column of checkboxes used to click to mark the test case as Blocked. I am trying to save the state of checkbox after it is submitted, but I am unable to do so.
Please help!
echo "<form id=\"checkbox\" class=\"check2\" method = \"post\" action=\"\">";
$checked = "";
if(isset($_POST['Blocked[]'])) {
$checked = 'checked="checked"';
}
echo "<td $Blocked><input type =\"checkbox\" name=\"Blocked[]\" value=\"checkblock\" onclick=\"showMsg('div1')\" $checked/></td>";
echo "<input type=\"submit\" value=\"Submit\" class=\"button\" name=\"edit_tc\" onclick=\"myFunction(form)\" style=\"position:fixed; height:25px ; width:150px; bottom:25px; right:200px;\"/>";
echo "</form>";
Firstly, please don't echo the static html like above because it makes the code reading difficult. Secondly, you are using the isset() function incorrectly. Thirdly, your input field name for checkbox is of type array. Do you really need this to be an array?
Please use something like this:
<?php
$checked = '';
if(isset($_POST['Blocked'])) {
$checked = 'checked="checked"';
}
?>
<form id="checkbox" class="check2" method = "post" action="">
<input type ="checkbox" name="Blocked" value="checkblock" onclick="showMsg('div1')" <?php echo $checked;?>/>
<input type="submit" value="Submit" class="button" name="edit_tc" onclick="myFunction(form)" style="position:fixed; height:25px ; width:150px; bottom:25px; right:200px;"/>
</form>

php checkbox insert 0 if not check

I have a checkbox in PHP and I would like to have it checked if the value of the checkbox in the database is 1 and insert "0" in the database if saved and not checked
sample checkbox
<input type="checkbox" name="chckpagibigcon" <?php
if(isset($_POST['chckpagibigcon'])){
echo 'checked value = "0"';
}else{
echo 'value = "1"';
}
?>>
Pretty good solution would be:
<input type='hidden' name='chckpagibigcon' value='0'/>
<input type='checkbox' name='chckpagibigcon' value='1' <?php echo (isset($_POST['chckpagibigcon']))?'checked':'';?>/>
Try this one:
<input type="checkbox" name="chckpagibigcon" <?php
if(isset($_POST['chckpagibigcon'])){
echo 'checked value = "1"';
}else{
echo 'value = "0"';
}
?>>
Just revers your condition.

Categories