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.
Related
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.
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.
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.
in database values are stored as "A,B,C,D,E,F" etc.
now i have to fetch those data in the form for update.
i have to check the checkbox if it matches the value with database value.
i am doing this kind of code(which i know is wrong)
<input type="checkbox" name="time[]" value="free" <?php if(!strpos($row['best'], 'free')=="false") { echo "checked='checked'";} ?> />Free
<input type="checkbox" name="time[]" value="Open" <?php if(!strpos($row['best'], 'Open')=="false") { echo "checked='checked'"; }?>/>Open Source
<input type="checkbox" name="time[]" value="portable" <?php if(!strpos($row['best'], 'portable')=="false") { echo "checked='checked'"; } ?> />Portable
<input type="checkbox" name="time[]" value="support" <?php if(!strpos($row['best'], 'support')=="false") {
echo "checked='checked'"; }?> />Support
When strpos is 0 (first character), then it is equal to false if you use double = (==). You need to use ===false. Besides it should be false, not "false".
You can do in this way:
suppose you have four static values :
<
?php
$time = ['free', 'open' , 'portable', 'support']; // your checkboxes
$fromDb = explode(',', $row['best']);
foreach($time as $t):
?>
<input type="checkbox" name="time[]" value="<?php echo $t;?>" <?php if(in_array($t, $fromDb) { echo "checked='checked'";} ?> /><?php echo ucfirst($t);?>
<?php endforeach;?>
I have a page where I am displaying sql results as a table. I have it so that all the options are checked on default. However, when the user unchecks some locations and submits the form, he/she won't know what locations they're filtering on because all the checkboxes will still be checked. How can I make it so that only the checkboxes that were checked retain their value after the form is submitted?
Thank you
Here's my page so far:
<?php
$start=_GET['start'];
$end=_GET['end'];
if(empty($start)){
$start=date("Ym");
}
if(empty($end)){
$end=date("Ym");
}
$places=array();
if(!empty($_GET['cities'])){
foreach($_GET['cities'] as $loc){
array_push($places,$loc);
}
}else{
$places=('CHI','DET','LA','NYC','DALLAS','SPR','PHI');
}
?>
//html
<form method='GET'>
START:<input type='text' name='start' value= '<?$start?>'>
END: <input type='text' name='end' value='<?$end?>'>
<input type='checkbox' name='cities[]' value='CHI' checked>CHICAGO
<input type='checkbox' name='cities[]' value='DET' checked>DETROIT
<input type='checkbox' name='cities[]' value='LA' checked>LAS ANGELES
<input type='checkbox' name='cities[]' value='NYC' checked>NEW YORK
<input type='checkbox' name='cities[]' value='DALLAS' checked>DALLAS
<input type='checkbox' name='cities[]' value='SPR' checked>SPRINGFIELD
<input type='checkbox' name='cities[]' value='PHI' checked>PHILIDELPHIA
<input type='submit' value='Filter'>
</form>
<?
$SQL="SELECT NAME,
ID,
PHONE,
EMAIL,
EVENT,
LOCATION
FROM SHOPPERS
WHERE LOCATION IN ('".implode("', '", $places)."')
AND EVENT BETWEEN '{$start}' and '{$end}'
AND ID BETWEEN '25687' AND '28050'
";
//and then fetch array to print out results...
.....
?>
Rather than hard-coding your "checked" attribute into each of your <input type="checkbox"> fields, you should be using PHP to determine if the GET variable associated with each field was passed to the script. In that case, you want to append the checked attribute to your <input> field. You can accomplish this by using a ternary operator right inside the field, as such:
<input type='checkbox' name='cities[]' value='CHI' <?= (in_array('CHI', $places)) ? 'checked' : ''; ?> >CHICAGO
<input type='checkbox' name='cities[]' value='DET' <?= (in_array('DET', $places)) ? 'checked' : ''; ?> >DETROIT
<input type='checkbox' name='cities[]' value='LA' <?= (in_array('LA', $places)) ? 'checked' : ''; ?> >LAS ANGELES
<input type='checkbox' name='cities[]' value='NYC' <?= (in_array('NYC', $places)) ? 'checked' : ''; ?> >NEW YORK
<input type='checkbox' name='cities[]' value='DALLAS' <?= (in_array('DALLAS', $places)) ? 'checked' : ''; ?> >DALLAS
<input type='checkbox' name='cities[]' value='SPR' <?= (in_array('SPR', $places)) ? 'checked' : ''; ?> >SPRINGFIELD
<input type='checkbox' name='cities[]' value='PHI' <?= (in_array('PHI', $places)) ? 'checked' : ''; ?> >PHILIDELPHIA
you could send the parameter which checkbox is checked in GET request,
and check it in your page
e.g
if ($_GET['param1']==1) // checked
{
?>
<input type='checkbox' name='cities[]' value='CHI' checked>CHICAGO
<?
else
?>
<input type='checkbox' name='cities[]' value='CHI' >CHICAGO
?>
<?php
$citiesGroup = array();
$citiesGroup['CHI'] = 'CHICAGO';
$citiesGroup['DET'] = 'DETROIT';
$citiesGroup['LA'] = 'LAS ANGELES';
$citiesGroup['NYC'] = 'NEW YORK';
$citiesGroup['DALLAS'] = 'DALLAS';
$citiesGroup['SPR'] = 'SPRINGFIELD';
$citiesGroup['PHI'] = 'PHILIDELPHIA';
$citiesChecked = array();
if (!empty($_GET['cities'])) {
foreach ($_GET['cities'] as $cityCode) {
$citiesChecked[] = $cityCode;
}
}
else {
foreach ($citiesGroup as $key => $value) {
$citiesChecked[] = $cityCode;
}
}
?>
<?php
foreach ($citiesGroup as $cityId => $cityName) {
$chekced = in_array($cityId, $citiesChecked) ? 'checked="checked"' : '';
?>
<input type='checkbox' name='cities[]' value='<?php echo $cityId;?>' <?php echo $chekced;?>><?php echo $cityName;?>
<?php
}
?>
Get all checkboxed HTML in array and loop over it.
Above is the working code.