Post values of a checkbox - php

I have this code on my form for the checkboxs:
<input type="hidden" name="option_desc[]" value="option 1"/>
<label><input type="checkbox" name="option_price[]" value="10" class="option_checkbox"/>option 1</label>
<input type="hidden" name="option_desc[]" value="option 2"/>
<label><input type="checkbox" name="option_price[]" value="20" class="option_checkbox"/>option 2</label>
<input type="hidden" name="option_desc[]" value="option 3"/>
<label><input type="checkbox" name="option_price[]" value="30" class="option_checkbox"/>option 3</label>
I'm trying to get the POST values of the checkbox that the user checked (for example, if he checked the second checkbox: "option 2" + "20") and store them:
$articleDetails['options'] = array();
$count = 0;
if(is_array($_POST['option_price'])){
foreach($_POST['option_price'] as $key => $value){
if($value){
$articleDetails['options'][$count]['option_price'] = $_POST['option_price'][$key];
$articleDetails['options'][$count]['option_desc'] = $_POST['option_desc'][$key];
$count++;
}
}
}
When the user check one of the checkbox, the appropriate 'option_price' is stored correctly, but the 'option_desc' is not the one that belongs to the CHECKED checkbox (for example: when the second checkbox is checked the values that I get are "20" (GOOD) and "option 1" (NOT GOOD).
What I'm doing wrong?
Thanks.

The problem you are having is that if checkboxes are not checked, the data won't get POSTed while your hidden inputs will always be posted. Frankly, I don't see what value your hidden inputs give you here. They tell you absolutely nothing about the posted data that you don't already know about on the server.
You should simply use a defined index in your array notation for the checkbox field, like this:
<input type="checkbox" name="option_price[1]" value="10" class="option_checkbox"/>option 1</label>
<input type="checkbox" name="option_price[2]" value="20" class="option_checkbox"/>option 2</label>
<input type="checkbox" name="option_price[3]" value="30" class="option_checkbox"/>option 3</label>
Note: I didn't use zero-indexed array here as I figured you might want to directly relate $_POST['option_price'][1] to "option 1".
To add some examples related to the discussion in comments below. Say for example you had some option_price checkboxes you want to output, and they come from some dynamic source. Your code to to generate the checkboxes might look something like this:
$price_options = array(
array(
'description' => 'eBook',
'value' => 10
),
array(
'description' => 'articles',
'value' => 20
),
// and so on
);
$count = count($price_options)
for($i = 1; $i<= $count; $i++) {
?>
<input type="checkbox" name="option_price[<?php echo $i; ?>]" value="<?php echo $price_options[$i]['value']; ?>" class="option_checkbox"/><?php echo $price_options[$i]['description']; ?></label>
<?php
} // end for
When POSTing you know that every $_POST['option_price'][x] would correspond to the item at $price_options[x].
You could simply iterate of $_POST['option_price'] to see which items are selected like this:
if(!empty($_POST['option_price']) {
foreach ($_POST['option_price'] as $index => $value) {
// verify value hasn't been tampered with
if ((int) $value === $price_options[$index]['value']) {
// set description
$description = $price_options[$index]['description'];
var_dump($description, $value);
}
}
}

I would suggest give names to input like
<input type=hidden name="option[1][desc]"/>
<input type=hidden name="option[1][price]"/>
Then I think it would be easy to run a forreach as well.

Related

Set the uncheck checkbox to 0 without using hidden textbox

Im trying to get all of the checked values using array i already get all of the checked box and get the value but my problem is i want to pass to array all of value of checbox, 1 for check and 0 for uncheck. sorry for the english.
this is what i want to get:
array[0] = 1 //check
array[1] = 0 // uncheck
// and so on.
i have already tried a hidden box with same name of checkbox but it give me wrong data of array and i am sure its not the answer
<input type = "checkbox" name="checkbox[]" value="1">
$checkbox1 = ($_POST['checkbox'] <> 0) ? ($_POST['checkbox']) : (empty($_POST['checkbox'])) ?'0' : '';
output: 0
output of print_r($checkbox1) : 0
expected output : array[0]=> 1 --> check array[1] => 0 -> uncheck
When working with a PHP backend where you want to post an array of values (using the name="something[]" syntax) you need to create <input type="hidden"> and <input type="checkbox"> pairs that will refer to the exact same array index.
You do so by explicitly defining the index in the name attribute.
For example
<input type="hidden" name="checkbox[0]" value="0">
<input type="checkbox" name="checkbox[0]" value="1">
<input type="hidden" name="checkbox[1]" value="0">
<input type="checkbox" name="checkbox[1]" value="1">
<input type="hidden" name="checkbox[2]" value="0">
<input type="checkbox" name="checkbox[2]" value="1">
I believe this also works for ASP.NET-MVC backends. Not sure about others though.
If you're looping over records or a range, this is as simple as keeping an iteration index and using it in the name attributes
<?php for ($i = 0; $i < $range; $i++): ?>
<input type="hidden" name="checkbox[<?= $i ?>]" value="0">
<input type="checkbox" name="checkbox[<?= $i ?>]" value="1">
<?php endfor ?>

Use database to check a checkbox

I have a page to view assets with an Edit link. When I click the link it goes to edit_case.php which has a form to edit what elements of the row are in the database as checkboxes. However the boxes do not show them as checked. I have the following code...
// get already checked box values
$repop = "SELECT * FROM case_audit WHERE case_id = $case_id";
$popresults = mysqli_query($dbc, $repop);
$row = mysqli_fetch_array($popresults, MYSQLI_ASSOC);
print_r ($row);
The print_r does show the whole record row from DB. which is either a 1 or 0, checked || not checked.
The form...
<div id="facepics">
<label><input type="checkbox" name="Facial1" value="<?php echo $row['frontrest']; ?>" >Front at Rest </label><br>
<label><input type="checkbox" name="Facial2" value="<?php echo $row['frontbigsmile']; ?>" >Front Big Smille</label><br>
<label><input type="checkbox" name="Facial3" value="<?php echo $row['profile']; ?>" >Profile</label><br>
<label><input type="checkbox" name="Facial4" value="<?php echo $row['subvertex']; ?>" >SubMento Vertex</label><br>
</div>
I know I need to turn the 1's to "checked" just not sure how best to do that.
so basically checked="true" attribute in input creates a checked checkbox.
HTML Code looks like
<input type="checkbox" checked="true">
In your case you can do it like:
<input type="checkbox" name="Facial1" value="frontrest" <?= (intval($row['frontrest']) == 1) ? 'checked' : '';>
Also note that I changed value attribute, with frontrest so that you can identify the checkbox uniquely
EDIT: I have modified the code
<input type="checkbox" name="Facial1" <?=$row['frontrest']==1?'checked':''?>>
I often have the same issue where the browser ignores checked="false" and checks all
so I use
<input type="checkbox" checked>

PHP - Handling HTML checkbox array [duplicate]

I have 1 form in with multiple checkboxes in it (each with the code):
<input type="checkbox" name="check_list" value="<? echo $row['Report ID'] ?>">
Where $row['Report ID'] is a primary key in a database -so each value is different.
How would I be able to tell which checkboxes have been checked? (Maybe multiple)
This is for an inbox system and I have a button below that I want (when clicked) to delete all messages (ids of: $row['Report ID']) which have the checkbox's checked.
Set the name in the form to check_list[] and you will be able to access all the checkboxes as an array($_POST['check_list'][]).
Here's a little sample as requested:
<form action="test.php" method="post">
<input type="checkbox" name="check_list[]" value="value 1">
<input type="checkbox" name="check_list[]" value="value 2">
<input type="checkbox" name="check_list[]" value="value 3">
<input type="checkbox" name="check_list[]" value="value 4">
<input type="checkbox" name="check_list[]" value="value 5">
<input type="submit" />
</form>
<?php
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
echo $check; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
}
}
?>
Edit To reflect what #Marc said in the comment below.
You can do a loop through all the posted values.
HTML:
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
<input type="checkbox" name="check_list[]" value="<?=$rowid?>" />
PHP:
foreach($_POST['check_list'] as $item){
// query to delete where item = $item
}
you have to name your checkboxes accordingly:
<input type="checkbox" name="check_list[]" value="…" />
you can then access all checked checkboxes with
// loop over checked checkboxes
foreach($_POST['check_list'] as $checkbox) {
// do something
}
ps. make sure to properly escape your output (htmlspecialchars())
<input type="checkbox" name="check_list[<? echo $row['Report ID'] ?>]" value="<? echo $row['Report ID'] ?>">
And after the post, you can loop through them:
if(!empty($_POST['check_list'])){
foreach($_POST['check_list'] as $report_id){
echo "$report_id was checked! ";
}
}
Or get a certain value posted from previous page:
if(isset($_POST['check_list'][$report_id])){
echo $report_id . " was checked!<br/>";
}
It's pretty simple. Pay attention and you'll get it right away! :)
You will create a html array, which will be then sent to php array.
Your html code will look like this:
<input type="checkbox" name="check_list[1]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[2]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[3]" alt="Checkbox" value="checked">
Where [1] [2] [3] are the IDs of your messages, meaning that you will echo your $row['Report ID'] in their place.
Then, when you submit the form, your PHP array will look like this:
print_r($check_list)
[1] => checked
[3] => checked
Depending on which were checked and which were not.
I'm sure you can continue from this point forward.

Get each chekbox group values into separate variables upon form submission

I have multiple checkbox groups, and once the form is submitted, I want each group of checkboxes that were selected to be added to their own variable.
This is the form:
<form action="" method="get">
<p>apple <input type="checkbox" value="apple" name="fruits[]" /></p>
<p>orange <input type="checkbox" value="orange" name="fruits[]" /></p>
<p>peach <input type="checkbox" value="peach" name="fruits[]" /></p>
<br>
<p>red <input type="checkbox" value="red" name="colors[]" /></p>
<p>green <input type="checkbox" value="green" name="colors[]" /></p>
<p>blue <input type="checkbox" value="blue" name="colors[]" /></p>
<br>
<p>chicken <input type="checkbox" value="chicken" name="meats[]" /></p>
<p>pork <input type="checkbox" value="pork" name="meats[]" /></p>
<p>lamb <input type="checkbox" value="lamb" name="meats[]" /></p>
<button>submit</button>
</form>
And this is my code:
$string = 'fruits,colors,meats';
$str_array = explode(',', $string);
foreach ($str_array as $value) {
if (isset($_GET[$value])) {
$group_name = $_GET[$value];
foreach ($group_name as $group_item) {
$group_string .= ' ' . $group_item;
}
}
}
echo $group_string;
With that code, if I choose for example the first checkbox in each group and hit submit, I will get the following value of $group_string = apple red chicken in one string.
What I get does make sense to me as per the code I wrote, but what I want is for each option group to have its own variable to which its values are asigned, so what I want is to get is the following (assuming I again chose the first option from each group):
$fruits = 'apple';
$colors = 'red';
$meats = 'chicken';
But I don't know how to rewrite it so I get that. Also, the number of options groups is not known upfront, it has to happen dynamically.
Ok, I took the liberty of rewriting part of your php for my convenience but here it is
your new and improved php file
<?php
// assume we know beforehand what we are looking for
$groups = explode(',','fruits,colors,meats');
foreach ($groups as $group) {
if (isset($_GET[$group])) {
$vv = array();
foreach ($_GET[$group] as $item) $vv[] = $item;
$$group = implode(' ',$vv);
}
}
var_dump($fruits,$colors,$meats);
?>
I used a construct in PHP called variable variables. This is actually an almost identical answer as the one #Lohardt gave. I hope this can help you out. If it doesn't then post me a comment
You could do something like:
<input type="checkbox" value="apple" name="groups[fruits][]" />
<input type="checkbox" value="apple" name="groups[colors][]" />
<input type="checkbox" value="apple" name="groups[meats][]" />
Your $_POST will look like this:
Array
(
[groups] => Array
(
[fruits] => Array
(
[0] => apple
)
[colors] => Array
(
[0] => red
)
)
)
And it should be simple to use a foreach loop to get the keys and values.
Edit: then you can assign the value to variables like this:
${$key} = $value;
and use it you would do any variable:
echo $color;

Checked radio that is insert in database when select

Assuming this that we in time insert data in database has 3 input:radio and with select one from they, insert value it to database. now how in select from database same radio that inserted in database, is checked.
Example:
We have 3 input:radio as:
<input type="radio" name="type1" value="value1">
<input type="radio" name="type2" value="value2" checked>
<input type="radio" name="type3" value="value3">
With checked value2 inserted it in database, now we want show(select) all radios and checked it radio that is inserted to database.as(this is after select from database):
<input type="radio" name="type1" value="value1">
<input type="radio" name="type2" value="value2" checked> // this value was in the database
<input type="radio" name="type3" value="value3">
How can fix it with PHP?
You should, as alreay said, use the same name for the radio buttons. Also, the right sintax is checked="checked" :
<input type="radio" name="type" value="value1">Value 1
<input type="radio" name="type" value="value2" checked="checked">Value 2
<input type="radio" name="type" value="value3">Value 3
When retrieved from database, you can check if value equals to the one in your html, and set a checked attribute accordingly.
<input type="radio" name="type" value="value1" <?php echo ($query_hs->type == 'value1') ? 'checked="checked"' :'';?>>Value 1
<input type="radio" name="type" value="value2" <?php echo ($query_hs->type == 'value2') ? 'checked="checked"' :'';?>>Value 2
<input type="radio" name="type" value="value3" <?php echo ($query_hs->type == 'value3') ? 'checked="checked"' :'';?>>Value 3
Just substitute your own values with my standard one, like:
<input type="radio" name="type" value="hotel" <?php echo ($query_hs->type == 'hotel') ? 'checked="checked"' :'';?>>Hotel
First of all, name of the radio element should be same for all three radio buttons so that they form a group. Otherwise, your users will be able to select all three.
Second, define the set of values as array in PHP. And run a forloop to generate HTML code. Something on these lines -
<?php
$radio_values = array("value1", "value2", "value3"); // Assuming your set of values is static
foreach($radio_values as $value) {
$value_from_db = read_radio_value(); // Replace this with your logic to fetch values from database
if ($value_from_db == $value) $checked = "checked";
else $checked = "";
echo "<input type=\"radio\" name=\"type\" value=\"{$value[$i]}\" {$checked}>";
}
?>

Categories