Populating checkboxlists from database - php

Is it possible to populate a checkboxlist from the database values? If so, please suggest how to do this.
$query2 = "select * from Products where CategoryID = '$CategoryName' ";
mysql_query($query2) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($query2)){
$array[] = $row;}
foreach($array as $val)
{
if($val =='the checkbox value')

<form>
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br />
<input type="checkbox" name="vehicle" value="Car" /> I have a car
</form>
These are the few steps you have to do.
1.Fetch the values from database.
2. Covert the values in array as they are stored as string by (,) separated.
3. Then
foreach($values as $val)
{
if($val =='Bike')
{
$bikeflag = '1';
}
if($val =='Car')
{
$carflag = '1';
}
}
<form>
<input type="checkbox" name="vehicle" value="Bike" <?php if(isset($bikeflag ) =='1'){ ?>checked = checked <?php } ?>/> I have a bike<br />
<input type="checkbox" name="vehicle" value="Car" <?php if(isset($carflag) =='1'){ ?>checked = checked <?php } ?>/> I have a car
</form>
Hopefully this will help you.

Get values from database with the appropriate SQL query
Loop through results echoing out a checkbox element
Caveats
Make sure each one has a unique name unless you want them to be an array. Then use array syntax for their name (e.g. name[])
Make sure to give each one a unique value

Yes, its very much possible:
Fetch the records to be populated with the structure:
Id and value
Provide datasource of the checkedbox list as the fetched structured list as mentioned above.
Now define the value field of the checkboxlist as "Id" and text as "value"

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;
}
}

update multiple checkbox data by using loop

There are multiple checkbox about 50+ for user access, checkbox are like follows;
<input name="PREFIX_1" type="checkbox">
<input name="PREFIX_2" type="checkbox">
<input name="PREFIX_3" type="checkbox">
...........
I have multiple checkbox with its respective values which I loop through to add/update the values in the database, which is like follows:
foreach ($_POST as $field => $value ) {
if ( preg_match('/^PREFIX_/', $field) ) {
$access = isset($value)?'1':'0';
$file = substr($field, 4);
$this->db->query('UPDATE_DESIRED_TABLE');
}
}
The problem is when I add/update the values in the database by using loop foreach ($_POST as $field => $value ) and checking the prefix, I only get values of checkbox that are checked and the values of data that are not checked are not in the $_POST data.
And, I don't get any values which are not checked, which is not even the name of that checkbox. In other words only those values are set which are checked.
Now I have to change the value of all the data in the database by comparing both the data in the database and from the post data.
How can I solve this?
You would need to send hidden inputs along with the checkboxes like this:
<form action="" method="post">
<input type="hidden" id="PREFIX_1_" name="PREFIX_1" value="0">
<input type="checkbox" id="PREFIX_1" name="PREFIX_1" value="1" />
<input type="hidden" id="PREFIX_2_" name="PREFIX_2" value="0">
<input type="checkbox" id="PREFIX_2" name="PREFIX_2" value="1" />
<input type="hidden" id="PREFIX_3_" name="PREFIX_3" value="0">
<input type="checkbox" id="PREFIX_3" name="PREFIX_3" value="1" />
<input type="submit" name="sub" value="Go" />
</form>
However you cant use the isset anymore with this, change PHP like this:
if(isset($_POST['sub']))
{
foreach ($_POST as $field => $value )
{
if ( preg_match('/^PREFIX_/', $field) )
{
$access = $value;
$file = substr($field, 4);
$this->db->query('UPDATE_DESIRED_TABLE');
}
}
}
Considering you know the number of checkbox, stored in example in $checkBoxCount, you might use this kind of loop :
for ($i = 1; $i <= $checkBoxCount; $i++)
{
$access = ((isset($_POST["PREFIX_" . $i])) ? ('1') : ('0')));
//manage DB
}

How do I insert multiple checkbox values with different name?

I want to store multiple checkbox value in database ,and my checkbox name is differnt,how can save ??.I have three column like Called them,Called you,toured, how i can store each value in data base.
HTML Code
<input type="checkbox" name="Called_them[]" value="1">1<br>
<input type="checkbox" name="Called_them[]" value="2">2<br>
<input type="checkbox" name="Called_you[]" value="1">1<br>
<input type="checkbox" name="Called_you[]" value="2">2<br>
PHP Code:-
if(isset($_POST['submits']) )
{
$checked = $_POST['alled_them'];
$checked1 = isset($_POST['alled_them']);
for($i=0; $i < count($checked); $i++){
$tellfriend=new MemberEmails;
$tellfriend->called_them = isset($checked[$i])==0?'':$checked[i];
$tellfriend->save();
}
if(isset($_POST["submit"])) {
foreach($_POST['called_them'] as $called_them) {
//do things
}
foreach($_POST['called_you'] as $called_you) {
// do things
}
}
$array_called_them = $_POST['called_them'];
$array_called_them = $_POST['called_you];
You now have both checkbox groups as arrays. if you want the value from the array just use foreach on each of the arrays.

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.

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