Updating Already Checked Checkboxes in PHP - php

let's say I have a list of checkboxes that the user selects.
<input type="checkbox" name="utility[]" id="utility[]" value="Water" />Water<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />
etc...
The user selected Water and it is added to the database. Now the user wants to update the list:
<input type="checkbox" name="utility[]" id="utility[]" value="Water" checked="checked"/>Water<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />
etc...
How can I check that the utility has already been checked in PHP?

What I've done in the past, to save having hundreds of lines of bloat is this...
First compile all the html in a variable, without any "checked" instances.
$boxes = '';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Water" />Water<br />';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />';
Now I loop over your array of fields to check. I've provided a sample array here too.
$already_checked = array('Water', 'Electricity');
foreach( $already_checked as $ac ) {
$find = 'value="' . $ac . '"';
$replace = $find . ' checked="checked"';
$boxes = str_replace($find, $replace, $boxes);
}
echo $boxes;

You could do something like this:
<input type="checkbox" name="utility[]" value="Water"
<?= in_array('Water', $utilities) ? 'checked="checked"' : '' ?>"
/>
(The $utilities variable above is a stand-in for something like $_REQUEST['utilities'], depending on how your code is structured.)

Like that?
<input type="checkbox" name="utility[]" id="utility[]" value="Water"
<?php
if(isAlreadyChecked("Water"))
echo "checked=\"checked\""
?>
/>Water<br />
<?php
function isAlreadyChecked(value)
{
//Check if it is already checked and return a boolean
}
?>

I tried every variant of the in_array conditional out there and could NEVER get this to work (checking off the checkboxes whose values had been previously selected and thus inserted into the database). I tried complex queries with table joins and no luck with that either. I finally gave up and generated a display:hidden div that opened the array (which for some odd reason I had to IMPLODE rather than explode) and listed its items as comma-separated text. Then I tossed in a little jQuery indexOf() magic to determine if the value of each checkbox was part of said array or not. Took me 10 minutes flat to do this with jQuery, very simple.
Here's some sample code that is live and working fine:
<div class="categories">
<span class="keywords"><?php $categories = array(); $categories = implode(', ', $keywords); echo $categories ?></span>
<em>Please verify category selections with each update.</em><br/>
<?php
include 'db.php';
$sql = mysqli_query($con,"SELECT * FROM categoriesTable ORDER BY Category_Name ASC");
while ($row = mysqli_fetch_assoc($sql))
{
$key = urldecode($row['Category_Name']);
$id = urlencode($row['catID']);
echo "<input type='checkbox' name='Category_Key[]' value='$id' id='cat_$id' $chk> $key<br/>";
}
?>
</div>
CSS sets that div to invisible:
.keywords { display:none; visibility:hidden; }
and the jQuery portion:
$(document).ready(function() {
$('.categories input').each(function(index,data) {
var str=$('.keywords').text();
var catid = $(this).val();
var chk = str.indexOf(catid);
if (chk >= 0) {
$(this).prop('checked', true);
}
});
});
I hope this helps someone else who is stuck wondering why the in_array conditional is failing them. Since this falls in a twilight zone between data and UI regarding data persistence, I think it's a legit route to take. You have one "echo" statement to generate multiple checkboxes (there are around 40 categories in my situation here) and then a simple jQuery .each() to locate what was selected before and render its corresponding boxes as checked.

Related

How to display checked check boxes together with non-checked ones

I have 5 check boxes from which a user can select one or more choices. The selected choices are then updated in database. The user's choices are then displayed/reviewed on another page. However my issue is that I want to show the updated choices together with the non-selected choices when doing a foreach loop in PHP.
These are the 5 check boxes
<input type="checkbox" name="interest[]" value="fishing">Fishing
<input type="checkbox" name="interest[]" value="camping">Camping
<input type="checkbox" name="interest[]" value="hiking">Hiking
<input type="checkbox" name="interest[]" value="swimming">Swimming
<input type="checkbox" name="interest[]" value="running">Running
<br><br>
<input type="submit" name="submit" value="Submit">
Heres the code that updates
if (isset($_POST["submit"])) {
$interestArr = $_POST['interest'];
$interest = new Interest();
$newArr = implode(',', $interestArr);
$interest->updateInterests($id=19, $newArr);
}
Heres the code that displays
<?php
$interest = new Interest();
$interests = $interest->showInterests($userid=19)->interests;
$newArr = explode(',', $interests);
foreach ($newArr as $data) {
echo '<input type="checkbox" name="interest[]" value="'.$data .'" checked>'.$data;
}
The update choices are stored under the interests column in DB like so
fishing,camping,running
And the foreach loop displays them checked check box with the correct corresponding labels.
How can I display the other check boxes that were not selected just so that the user might want to make changes?
Thanks.
Here's a simple example to illustrate the main idea. This code is intended to run in the single script.
The main ideas are:
Use a global list of interests to drive the form.
Keep a separate global list of checked check boxes which you can compare to determine if the checkbox should be checked.
when the form is submitted, populate the list which keeps track of checked items
render the form and compare the list of available checkboxes with checked checkboxes. If item found in both lists, it means that we want to display the checkbox as checked.
index.php
<?php
// Keep this outside of the if statement so the form has access to it.
$availableInterests = [
'fishing',
'camping',
'hiking',
'swimming',
'running',
];
// Keep this outside of the if statement so the form has access to it.
$selectedInterests = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Cast the posted interests to an array in case the user submitted an empty list.
// An empty list would be NULL if we didn't cast it.
$selectedInterests = (array)$_POST['interest'];
// foreach $selectedInterests insert into DB...
// Let this code `fall through` to render the form again.
// $selectedInterests is now populated and can be used in to the form below to keep the selected checkboxes checked.
}
?>
<form method="post">
<!-- Using the `global` $availableInterests array to drive our form. -->
<? foreach ($availableInterests as $interest): ?>
<!-- Do we want to render the checkbox as checked? -->
<?php $checked = (in_array($interest, $selectedInterests)) ? ' checked' : ''; ?>
<input type="checkbox"
name="interest[]"
value="<?php echo $interest; ?>"
<?php echo $checked; ?>>
<?php echo ucfirst($interest); ?>
<?php endforeach; ?>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
Let's suppose you have an array of choice list like :
$choices = ["Fishing", "Camping" , "Hiking","Swimming" , "Running" ]
after the user select their choices
$interests = ["Fishing" , "Running" ];
In your case , the coresponding line is :
$interest = new Interest();
$interests = $interest->showInterests($userid=19)->interests;
$newArr = explode(',', $interests);
Let's suppose that $newArr is equal to $interests in may example.
foreach ($interests as $interest) {
echo 'you have choose '.$interest.PHP_EOL;
}
As result :
you have choose Fishing
you have choose Running
For not selected :
$notInterests = array_diff($choices,$interests);
foreach ($notInterests as $notInterest) {
echo 'you have not choose '.$notInterest.PHP_EOL;
}
As Result :
you have not choose Camping
you have not choose Hiking
you have not choose Swimming
To handle it in one loop :
foreach ($choices as $choice) {
if(in_array($choice,$interests )){
echo'you have choose '.$choice.PHP_EOL ;
}else{
echo 'you have not choose '.$choice.PHP_EOL;
}
}
Hope this help you.
To help others that might be in a similar situation I would like to post what is now a working solution at least for me based on Mohammed Yassine CHABLI's inspiration. Vantiya who was the first to comment really help me appreciate what was to follow. Thanks guys.
<?php
$interest = new Interest();
$interests = $interest->showInterests($userid=19)->interests;
$choices = $interest->showInterests($userid=19)->choices;
$selected = explode(',', $interests);
$choices = explode(',', $choices);
foreach ($choices as $choice) {
if(in_array($choice,$selected )){
echo '<input type="checkbox" name="interest[]" value="'.$choice .'"
checked>'.$choice;
}else{
echo '<input type="checkbox" name="interest[]" value="'.$choice .'"
unchecked>'.$choice;
}
}

Store the array elments based on checkbox checked?

I've got this problem that I can't solve. Partly because I can't explain it with the right terms. I'm new to this so sorry for this clumsy question.
Below you can see an overview of my goal. I am displaying my check boxes in a for loop.
Here I am getting the all values in an array, but I want store the array elements based on the check box checked.
<?php
$j=0;
$arr = Array();
foreach($collection as $data) {
$mageid=$data['mageproductid'];
$products = Mage::getModel('catalog/product')->load($mageid);
$productMediaConfig = Mage::getModel('catalog/product_media_config');
$checkeven=0;
$arr[$j]=$products->getId();
//echo $arr[$j];
$j++;
} ?>
My checkbox code:
<form id="check_all" action="" method="POST" name="check" >
<input type="checkbox" class="multid[]" id="<?php echo $products->getId();?>" value="checked" /> </form>
What do I have to do in order to get checked values in my array? Did I do anything wrong?
Use input name attribute
<input type="checkbox" name="multid[<?php echo $products->getId();?>]" value="checked" />
No in you php code, check if multid[yourProductId] is set, and store them if it is set.
<?php
$j=0;
$arr = Array();
foreach($collection as $data) {
$mageid=$data['mageproductid'];
$products = Mage::getModel('catalog/product')->load($mageid);
$productMediaConfig = Mage::getModel('catalog/product_media_config');
$checkeven=0;
$arr[$j]=$products->getId();
if(!empty($_GET['multid['.$arr[$j].']']))
its checked, do something.
//echo $arr[$j];
$j++;
} ?>
After submiting the form you can get an array of checked products with $_POST['multid']
Can you use javascript? Try this one.
HTML:
<input type="hidden" id="hdnCheckedIDs" value="" />
Before submit, on submit button's client click, Javascript:
var CheckedIDs = "";
for each checkbox
if(document.getelementbyid('multid1').checked)
CheckedIDs = CheckedIDs + document.getelementbyid('multid1').id;
document.getelementbyid('checkboxID') = CheckedIDs;
In PHP, you can use this comma seperated string $_POST['hdnCheckedIDs'] to get the IDs of checked chekboxes.

Retrieve POST checkbox data from form if they exist

Hello knowledgeable people. I am having trouble retrieving checkbox data from form. I have a site in which user can add checkboxes themselves, so I am writing them out like this:
<table style="padding:10px;">
<?php
$query_boolean = $DB->prepare("SELECT * FROM moduls WHERE type='boolean'") or die(mysql_error());
$query_boolean->execute();
while (($row = $query_boolean->fetch()) != false)
{
?>
<tr>
<td>
<?php echo $row->name ?>:
</td>
<td>
<?php
$s = "";
$s .= sprintf('<input type="checkbox" class="textbox" name="boolean_%s" value="yes">%s', $row->id, Yes);
$s .= sprintf('<input type="checkbox" class="textbox" name="boolean_%s" value="no">%s', $row->id, No);
echo $s;
?>
</td>
</tr>
<?php
}
?>
</table>
Now I have an advanced search in which I have to chech through every checkbox to see what has been selected (ether none, Yes, No, or both). How can I get the info from every checkbox in variables? Thank you so much!
To get POST data from checkboxes they must have attribute
checked="checked"
EDIT:
If you have 2 checkbox as this..
<input type="checkbox" checked="checked" class="textbox" name="boolean_yes" value="yes">
<input type="checkbox" class="textbox" name="boolean_no" value="no">
When you submit your form the checkbox with attribute checked will be sent as POST and the one without checked attribute will not be sent..
if(isset($_POST['search'])) {
$all_checked = array();
foreach($_POST as $key=>$value){
if(strpos($key, "boolean_") > -1){
$all_checked[$key] = $value;
}
}
var_dump($all_checked);
}
This way you will get inside $all_checked array all marked boxes.. All others checboxes are not marked!
if you want to get checkbox value then use checkbox name as array
<input type="checkbox" name="email1[]" value="">
an get it on another page by
<?php
$var2 = $_POST['email1'];
$v=implode(",",$var2);
echo $v;
?>
try it

PHP: using post when mutliple form fields share same name & id

That title probably doesn't mean much but what I have is a form that is generated dynamically. I hooks into a table of products, pulls out there name. I then create a form that displays the product with a checkbox and textbox next to it.
<form id="twitter-feed" name="twitter-feed" action="<?php echo $this->getUrl('tweet/') ?>index/tweet" method="post">
<table><tr>
<?php
$model = Mage::getModel("optimise_twitterfeed/twitterfeed");
$products = $model->getProducts();
foreach ($products as $product){
echo '<tr>';
echo '<td>';
echo '<label for="'. $product .'">' . $product . '</label>';
echo '<br /><input type="text" class="hashtag" name="tags" id="tags" value="#enter, #product, #hastag"';
echo '</td>';
echo '<td><input type="checkbox" name="chk" id="'. $product .'"></td>';
echo '</tr>';
}
?>
<tr><td colspan="2"><input type="submit" name="submit" value="tweet"></td></tr>
</table>
</form>
As you can see there are checkboxes and textfields for each record. When I examine the $_POST data from the form it only retains fields for the last record.
Is there a way to pass all this data back to the action?
Cheers,
Jonesy
Use name="chk[]", then PHP will create an array for you.
Change your name arrtibutes to have an opening and closing square brace like this:
name="tags"
name="chk"
to
name="tags[]"
name="chk[]"
This will turn an array like:
$_POST['tags'][0] = VALUE
$_POST['tags'][1] = VALUE
$_POST['chk'][0] = VALUE
$_POST['chk'][1] = VALUE
Yes you can, set brackets at the end of the name value.
E.g.:
<input type="checkbox" name="chk[]" id="'. $product .'">
Then you get an array as result in $_POST['chk'].
Besides that, ids should always be unique. You can give same names, but you should always use different ids.
All of your fields have the same name, when that happens on any form you end up only seeing the last value because it's overwritten by the other fields.
Instead of <input type="checkbox" name="chk" id="124123"> do something like <input type="checkbox" name="chk[124123]" value='1'>
In your code you'd receive $_POST['chk'] as an array of values, only those values that were checked.
you can use as i have given example below. where i have taken one new variable $i = 0; and then you can use this $i into the foreach loop for displaying all product one-by-one..
i think this may help you.
$i = 0;
foreach ($products as $product){
echo '<td><input type="checkbox" name="chk" id="'. $product[$i] .'"></td>';
}

How to receive a batch of checkbox data in PHP?

The key code is:
while ($row= mysql_fetch_array($result, MYSQL_ASSOC))
{ $id=$row[id];
$html=<<<html
<tr><td>
<input style="float:left" type="checkbox" name="mycheckbox[]" value="$id">
<span style="float:left">$row[content]</span>
<span style="color:black;float:right">$row[submitter]</span></td></tr>
html;
echo $html;
}
There are many checkboxes.
How to receive these checkbox values in another PHP file?
You know, you need to name these checkboxes so a PHP file can receive these values on the other side. But how to name these checkboxes? If I name 1,2, 3,...,how can I associate them with $row[id]?
You need to give them names - you can either do it like this:
<input style="float:left" type="checkbox" id="$id" name="$id" value="true">
or like this to get an array:
<input style="float:left" type="checkbox" id="$id" name="myBoxes[$id]" value="true">
You can then check isset($_POST[$id]) or isset($_POST['myBoxes'][$id])
Name your checkboxes so you can easily identify them.
eg
$CheckBoxHTML = "<input type='checkbox' name='check_$row[id]' value='YES'>Check This";
then in your recieving php file you can find all checkboxes by
foreach ($_POST as $key => $value)
{
if (strpos($key,'check_') !== false)
{
list($tmp, $ID) = split('_', $key);
$CheckedValues[] = $ID;
}
}
That will pull out all your checked ids.

Categories