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']);
?>
Related
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;
}
}
I have an html form (and accompanying php code) that allows user to input task names, which are stored in a PHP array $task_list[].
I also have, below the task list, a dropdown from which users can select a desired value. I want to create a button modify which will allow users to change the value they have selected.
For instance, if the task list is:
Get up
Take a bath
Go for a jog
Go to school
Come back home
A user should be able to select "Go to school", and having done so, click Modify and change that to "Go to work", or something else.
I've made the select dropdown list work and can access the selected value and store it in a variable $selected. But I am completely flummoxed as to how I can allow users to change the value in the $task_list array.
My code–
task_list.php:
<form action="." method="post" >
<!//select dropdown>
<select name='taskid'>
<?php foreach( $task_list as $id => $task ) : ?>
<option value="<?php echo $id; ?>">
<?php echo $task; ?>
</option>
<?php endforeach; ?>
</select>
<?php foreach( $task_list as $task ) : ?>
<input type="hidden" name="tasklist[]" value="<?php echo $task; ?>">
<?php endforeach; ?>
<br />
<label> </label>
<input type="hidden" name="action" value='modify'>
<input type=submit value="Modify Task">
<br />
<label> </label>
<input type="hidden" name="action" value='promote'>
<input type=submit value="Promote Task">
</form>
index.php:
//get selected value
function getSelected()
{
if(isset($_POST['taskid']))
{
$myvalue = $_POST['taskid'];
}
else
{
$myvalue = $task_list[0];
}
return $myvalue;
}
//skipping ahead to modify field (all other buttons work perfectly):
case 'modify':
$myval = getSelected(); //$myval returns index of selected item
$selected = $task_list[$myval]; //selected item
break;
I just want to allow the user to click modify and change the value they selected in the $task_list array.
Thank you.
This is my form and categories comes from the database with while loop.
I want to insert the checked inputs only in to database.
How can i detect which checkbox is selected ?
<form action="account.php" method="POST">
<ul class="account-info">
<li>Category1 : <input type="checkbox" value="val1" name="cat1"></li>
<li>Category2 : <input type="checkbox" value="val2" name="cat1"></li>
<li>Category3 : <input type="checkbox" value="val3" name="cat1"></li>
<!-- while continues -->
<li>Category100 : <input type="checkbox" value="val100" name="cat1"></li>
</ul>
<input type="submit" value="submit" />
</form>
In account.php only the check boxes will be posted. As you've named them all the same though, only 1 will be posted, the last checkbox. If you want them to have the same name and come through as an array you need to add [] after the name, like this:
<input type="checkbox" value="val100" name="cat1[]">
Then in your account.php where they are submitted you can do this:
foreach($_POST['cat1'] as $val)
{
echo "$val<br>";
}
That will echo out the values of all the checked boxes.
First off, you have your options set up as if they were radio buttons all having the same name turning into 1 value out of the 3 possible. If you want them to be conventional checkboxes you have to give them separate names.
in your PHP you would check if the array_key_exists for the checkbox name in question, this is how I usually translate the checkbox fields in a form to be easier to use:
<?php
$checked = array(
'cat1' => array_key_exists('cat1', $_POST),
'cat2' => array_key_exists('cat2', $_POST),
'cat3' => array_key_exists('cat3', $_POST)
);
print_r($checked);
exit;
?>
change the name="cat1" to name="cat[1][]"
in your account.php page
foreach($_POST['cat'] as $category){
foreach($category as $value){
echo $value;
}
}
You can check it like that:
This code will check which categories are activated
assuming that your database returns categories from 0 to x
$i = 0;
while(true){
if ($_POST["cat".$i."]) {
//category activated
}
else {
//no category found -> loop ends
break;
}
$i++;
}
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.
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.