Store the array elments based on checkbox checked? - php

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.

Related

Why I cant submit this array to PHP?

I have a table with data and checkboxes aside. When I click in checkboxes I am taking the id of the item of each selected and when submit I am receiving in PHP BUT now I changed my approach. Now, I want to submit the entire array to PHP however I don't receive it:
<?php foreach ($arr_cases as $cases) : ?>
<tr>
<td>
<input type="checkbox" name="devices" value="<?php $dataa = serialize($cases); $encodedd = htmlentities($dataa); echo $encodedd; ?>">
</td>
</tr>
<?php endforeach; ?>
The way I am doing above, I can ONLY receive ONE array in PHP, so, tried naming the checkboxes from devices to devices[] but this time its printing blank(nothing).
I, of course, unserialize it in PHP.
What am I doing wrong here?
You need to use an array-style name for the checkbox so you receive all of them in an array.
<input type="checkbox" name="devices[]" value="<?php $dataa = serialize($cases); $encodedd = htmlentities($dataa); echo $encodedd; ?>">
Then $_POST['devices'] will be an array of all the checked values. Each element of this array will be serialized, and you'll have to unserialize it.
if (!empty($_POST['devices'])) {
$devices = array_map('unserialize', $_POST['devices']);
} else {
$devices = [];
}
var_dump($devices);

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

php array stored in session

still no solution on this question
So this is what I'm trying to do:
Have a product in a shopping cart with options. the options will be selectable through <input type="checkbox/> And the products are stored based on id's in sessions with php.
Right now I have the candies submitting as an array (like below) But I'm not sure how to add it to that specific product within the session.
My Input for the options is like this:
<?php foreach($options as $option): ?>
<input type="checkbox" name="candies[]" value="<?php echo $option['candy_name']; ?>" /><?php echo $option['candy_name']; ?><br/>
<?php endforeach; ?>
My current code for adding the product to the session is like this:
...
case "add":
$_SESSION['cart'][$product_id]++;
header('location: ../../cart.html');
break;
...
I've also placed $candies = $_GET["candies"]; above the above code to get the options.
How can I make it so the options array is stored in the session for each individual product?
In this image below, you can see what I'm talking about... I am wanting to display each selected option under the options column for the specific product.
this might not be the exact code you are looking for but this should serve as your guide to what you want to achieve.
Let's say you want to get the product options values from you database's productOptions.
$resultSet = mysql_query("SELECT * FROM productOptions");
Now we display the checkboxes to your form based on the result of the query.
while($row = mysql_fetch_assoc($resultSet)){
echo "<input type='checkbox' name='options[]' value='{$row['optionsID']}' />";
}
After displaying the check boxes to our form, we get the checked value from those check boxes that where selected.
if(isset($_POST['yourSubmitButtonName'])){
$productSelected = array();
if(!empty($_POST['options'])){
foreach($_POST['options'] as $options){
$optionsSelected[] = $options;
}
}
}
Now, set the array of options the the $_SESSION variable.
$_SESSION['yourProductID'] = $optionsSelected;
Then we display the options for a product this way
foreach($_SESSION['yourProductID'] as $productOptions){
echo $productOptions;
}
It looks like you've got the correct HTML structure but your code is disjointed. The simplest answer is to do something like this
$_SESSION['cart'][$product_id] = array('options' => $_POST['candies']);
Then you would do something like
foreach($_SESSION['cart'][$product_id]['options'] as $opt) {
echo $opt;
}
Code should look like this first html take checkbox
<form action="sample.php" method="post">
<input type="checkbox" name="candies[]" value="Candy1" />
<input type="checkbox" name="candies[]" value="Candy2" />
<input type="checkbox" name="candies[]" value="Candy3" />
<input type="submit" value="Submit" />
<form>
then session
<?php
session_start();
$result = array();
foreach ( $_POST['candies'] as $key=>$row ) :
$result[$key] = $row[$key];
endforeach;
$_SESSION['candies'] = $result;
print_r($_SESSION['candies']);
?>

Include also unchecked boxes in the POST variable - multiple checkbox

I am using the code below in my php file to get the values from a multiple checkbox.
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
update_comment_meta($check, 'consider', 1);
}
}
The problem is that this code is apparently putting in the array $_POST['check_list'] only the checked values.
My need is to perfom the function update_comment_meta also on uncheked values, by putting '0' as the third parameter instead of '1'.
For more details, I give the code generating the HTML form:
<form action="" id="primaryPostForm" method="POST">
<?php
$defaults = array(
'post_id' => $current_post);
$com= get_comments( $defaults );
foreach ($com as $co) {
if(get_comment_meta($co->comment_ID, 'consider', true)==1) {
?><input type="checkbox" name="check_list[]" value="<?php echo $co->comment_ID; ?>" checked="checked">
<?php }
else {
?><input type="checkbox" name="check_list[]" value="<?php echo $co->comment_ID; ?>" >
<?php
}}
</form>
Your usual help is always appreciated.
sending unchecked value to post is somewhat not that easy.Better solution is that you name checkbox in a way using which you can easily iterate over them in post page.
Use hidden input along with checkbox.Checkbox prioritize over hidden input.
<form>
<input type='hidden' value='0' name='check_box_con'>
<input type='checkbox' value='1' name='check_box_con'>
</form>
Now after submit, as both have same name , check_box_con will show hidden field value if unchecked , else will override and show original.
For more see
Post the checkboxes that are unchecked
Here is the solution I used ( based on PeeHaa comment):
if(!empty($_POST['check_list'])) {
foreach ($com as $co) {
if (in_array($co->comment_ID,$_POST['check_list']))
update_comment_meta($co->comment_ID, 'consider', 1);
else
update_comment_meta($co->comment_ID, 'consider', 0);
}
}
In fact POST variable works like this with checkboxes, so the simple way is to use server side language to know what are values not sent via POST.
Thank you for your time.

Populating checkboxlists from database

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"

Categories