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.
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'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>
I want the $delivery in the top input to change value depending on the value on another variable I'm using.
I'm just not sure how to place another if inside the current if and how to match up the value="0.00" so it all works together
<form action="" method="post" onclick="this.submit()">
<input <?php if ($delivery=='0.00'){ echo 'checked="checked"';} ?> type="radio" value="0.00" name="delivery"> Economy - up to 4 working days<br>
<input <?php if ($delivery=='4.99'){ echo 'checked="checked"';} ?> type="radio" value="4.99" name="delivery"> Express - next day <br>
<input <?php if ($delivery=='9.99'){ echo 'checked="checked"';} ?> type="radio" value="9.99" name="delivery"> Saturday<br>
</form>
Thanks.
What i ended up doing was this:
if ($pricetotal <= 50.00) {
$amount1 = 3.99;
}
elseif ($pricetotal >= 50.01) {
$amount1 = 0.00;
}
Then in my form changing it to this:
<form action="" method="post" onclick="this.submit()">
<input <?php if ($delivery<='3.99'){ echo 'checked="checked"';} ?> type="radio" value=" <?php echo htmlspecialchars($amount1); ?>" name="delivery"> Economy - up to 4 working days<br>
<input <?php if ($delivery=='4.99'){ echo 'checked="checked"';} ?> type="radio" value="4.99" name="delivery"> Express - next day <br>
<input <?php if ($delivery=='9.99'){ echo 'checked="checked"';} ?> type="radio" value="9.99" name="delivery"> Saturday<br>
I might not have explained exactly what i needed as i thought there would be a simple fix, but i wanted the top inputs value do change depending on $pricetotal and i managed to get it working.
Thanks for the help.
I would do something like this:
$deliveryEconomy = '';
$deliveryExpress = '';
$deliverySaturday = '';
switch($delivery)
{
case 0.00:
$deliveryEconomy = 'checked="checked"';
break;
case 4.99:
$deliveryExpress = 'checked="checked"';
break;
case 9.99:
$deliverySaturday = 'checked="checked"';
break;
}
<form action="" method="post" onclick="this.submit()">
<?php
echo "<input $deliveryEcononomy type='radio' value='0.00' name='delivery'> Economy - up to 4 working days<br>";
echo "<input $deliveryExpress type='radio' value='4.99' name='delivery'> Express - next day <br>";
echo "<input $deliverySaturday type='radio' value='9.99' name='delivery'> Saturday<br>";
?>
</form>
Normally you would run logic before this, but if you are looking for a quick and dirty mini-if statement, something like this might work for you:
if ($delivery==($boolVar ? '0.00' : 'something else')){ echo 'checked="checked"';}
These statements have the same result:
if($condition) {
$var = $statement_1;
} else {
$var = $statement_2;
}
$var = $condition ? $statement_1 : $statement_2;
Don't overuse it however, otherwise you may be tempted to try:
$var = $condition_1 ? $statement_1 : ($condition_2 ? $statement_2 : $statement_3);
Messy.
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.
I have the following code:
<select name="to" class="combo" value='
<?php
if(isset($_POST['reply']))
{
echo "<option value='$reply'>$reply</option>";
}
?>
' />
<?php
$q = $database->selectAllUsersNotMe();
while($row=mysql_fetch_assoc($q))
{
$u=$row['username'];
echo "<option value=\"$u\">$u</option>";
}
?>
</select>
What this does is produce a combo box with a dropdown for all users on my site excluding the user sending the message.
I am trying to add a reply element to the message.
When i click reply, i use the following code:
<? $reply = $_POST['rfrom']; ?>
<form name='reply' method='post' action='/newmessage.php'>
<input type='hidden' name='rfrom' value='<?php echo $pm->messages[0]['from']; ?>' />
<input type='hidden' name='rsubject' value='Re: <?php echo $pm->messages[0]['title']; ?>' />
<input type='hidden' name='rmessage' value='[quote]<?php echo $pm->messages[0]['message']; ?>[/quote]' />
<input type='submit' name='reply' value='Reply' />
</form>
The values are correct and definately pass the information using POST.
On the initial piece of code I provided, how can I alter this so the username that I am replying to is selected when I am replying, if not, the usernames are just listed.
Thanks
$fromname=(isset($_POST['rfrom'])) ? $_POST['rfrom'] : ''; //ought to validate $_POST
while($row=mysql_fetch_assoc($q)) {
$u=$row['username'];
$selected=($u==$fromname) ? 'selected="selected"' : '';
echo "<option value=\"$u\" $selected>$u</option>";
}
$replyUser = $_POST['rfrom'];
while($row = mysql_fetch_object($q))
{
if($row->username == $replyUser)
{
echo('<option value="'.$row->username.'" selected="selected">'.$row->username.'</option>');
}else{
echo('<option value="'.$row->username.'">'.$row->username.'</option>');
}
}