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;
Related
how to save multiple radio button in database using php without save button value.
my code :
$user_id = $_POST['user_id'];
foreach ( $_POST as $key => $val ) {
if ($key <> 'user_id') {
$bidder_interst_insert="INSERT INTO bidder_interest_list(id, bidder_id, bidder_interest_name) VALUES ('','$user_id','$val')";
$bidder_interst_insert_result = mysql_query($bidder_interst_insert);
if (mysql_affected_rows() > 0) {
$interest_list_success = "Thank you Successfull insert your interst list.";
$_SESSION['interest_list_success_msg'] = $interest_list_success;
} else {
$insert_error = "interst list Insert Error.";
$_SESSION['insert_error_msg'] = $insert_error;
header("location:interest_list.php");
}
}
}
This code work but database extra save in save button value how to solved this problem??
foreach ( $_POST as $key => $val ){
You are directly looping the $_POST, so the SAVE button value is also saving in the database. Take the values individually instead of looping the whole $_POST, then the SAVE button value won't be saved in the database.
And moreover you are using mysql functions which are deprecated, use mysqli or PDO.
EDIT::
Just take it the same way as u took user_id ==> $variablename = $_POST['fieldname'];
EDIT:::
Let me suppose i have a form like this
<form name="form1" id="form1" method="post" action="">
<input type="checkbox" name="products[]" value="A" checked="checked" />A <br />
<input type="checkbox" name="products[]" value="B" checked="checked" />B <br />
<input type="checkbox" name="products[]" value="C" checked="checked" />C <br />
<input type="checkbox" name="products[]" value="D" checked="checked" />D <br />
<input type="checkbox" name="products[]" value="E" checked="checked" />E <br />
<input type="checkbox" name="products[]" value="F" checked="checked" />F <br />
<input type="submit" name="save" id="save" value="Save" />
</form>
then i can do it like:
<?php
if(isset($_POST['save']))
{
$products = $_POST['products'];
foreach($products as $key => $value)
{
$qry = mysql_query("INSERT INTO tbl(product) VALUES('$value')");
}
}
?>
Try this
unset($_POST['name-of-save-button']);
$data = $_POST;
foreach ( $data as $key => $val ){//your code here}
A page is posting an array to me like this:
<input type="text" name="fields[email_address][value]" value="1" />
<input type="text" name="fields[first_name][value]" value="jim" />
<input type="text" name="fields[zip_code][value]" value="45254" />...
An array.
I can loop through it like this easy enough
foreach ( $_POST['fields'] as $key => $field ) {
echo $key." ".$field['value'] ;
}
Result of above:
first_name jim
email_address 1
address_postal_code 45254
But what I really need to do is reference just the zip (45254) out of the array, maybe like:
echo $_POST['fields']['zip_code']; //or
echo $_POST['fields']['zip_code']['value'];
result: 45254
Is this possible?
Update
<input type="text" name="fields[zip_code][value]" value="45254" />
to be
<input type="text" name="fields[zip_code]" value="45254" />
Edit: I wasn't aware you can't modify the html, that wasn't specified in the original question.
The only thing you can really do is do:
$_POST['fields']['zip_code'] = $_POST['fields']['zip_code']['value'];
However at that point, you might as well just assign $_POST['fields']['zip_code']['value'] to a variable and use that.
If you can't update the html of the form, all you can do is manipulate the data after it's been assigned to the $_POST superglobal like it's any other array
Edit 2: Adding a complete snippet to try:
If you do, what do you get?:
<?php
foreach ( $_POST['fields'] as $key => $field ) {
echo $key." ".$field['value'] ."<br />";
}
echo $_POST['fields']['zip_code']['value'] . "<br />";
$_POST['fields']['zip_code'] = $_POST['fields']['zip_code']['value'];
echo $_POST['fields']['zip_code'];
?>
I just tried that with a simple form of:
<form method="post" action="test.php">
<input type="text" name="fields[email_address][value]" value="1" />
<input type="text" name="fields[first_name][value]" value="jim" />
<input type="text" name="fields[zip_code][value]" value="45254" />
<input type="submit" />
</form>
And it works as expected.
This seems sloppy but it worked:
foreach ( $_POST['fields'] as $key => $field ) {
$$key = $field['value'] ;
}
echo $address_postal_code;
45254
echo $_POST['fields']['zip_code']['value']
returns nothing
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.
I have a form with check boxes.
I want it so that when a check box is checked, it includes an array.
<input type="checkbox" name="main" value="main" checked> Main/unsorted<br />
<input type="checkbox" name="art" value="art" checked> Art/literature/music<br />
<input type="checkbox" name="games" value="games" checked> Games/gaming<br />
If main is checked include the array 'main', if art is checked include the array 'art', etc.
I've tried, but I can't find a function that would work for this scenario.
Edit: I'm cheating a bit and am now doing it like so.
foreach($_GET as $get) {
$end = array_merge($end, $$get);
}
From your information it sounds like you want to merge an array depending on which checkboxes have been ticked? Am I correct in assuming this?
Is something like this what you are looking for?
<?php
$combinationArray = array();
$mainArray = array('item1','item2','item3');
$artArray = array('item4','item5','item6');
$gamesArray = array('item7','item8','item9');
if(isset($_POST['main']) && $_POST['main']=='main'){
$combinationArray = array_merge($combinationArray,$mainArray);
}
if(isset($_POST['art']) && $_POST['art']=='art'){
$combinationArray = array_merge($combinationArray,$artArray);
}
if(isset($_POST['games']) && $_POST['games']=='games'){
$combinationArray = array_merge($combinationArray,$gamesArray);
}
?>
HTML:
<form action="yourpage.php" method="post">
<input type="checkbox" name="main" value="main" checked> Main/unsorted<br />
<input type="checkbox" name="art" value="art" checked> Art/literature/music<br />
<input type="checkbox" name="games" value="games" checked> Games/gaming<br />
<button>
Submit
</button>
</form>
I have a piece of code that I'm not happy with at all:
// Search for checkboxes ('chk-1','chk-2','chk-3'...)
foreach ($_POST as $key => $val) {
if (substr($key, 0,3) == 'chk') {
$appObj->cats[] = intval(substr($key,4,strlen($key)));
}
I really don't like this as $_POST can contain upwards of 40+ variables and I am already applying logic to all other posted vars.
Has anyone got any ideas / solutions to achieving the above without cycling through every $_POST var?
The only way how you could avoid cycling trough all items and using strncmp, strpos or substr is building check-boxes as one array (lets have $key = 7 as example):
<input type="checkbox" name="chk[7]" />
And php:
foreach( $_POST['chk'] as $key => $val){
$appObj->cats[] = $key;
}
This would would, but it may create key gaping:
$_POST['chk'] = array(
0 => 'ON',
1 => 'ON',
7 => 'ON',
);
Which may cause problems when someone will try processing data with for loop.
Better approach is this one:
<input type="checkbox" name="chk[]" value="7" />
<input type="checkbox" name="chk[]" value="57" />
<input type="checkbox" name="chk[]" value="1231" />
And php:
foreach( $_POST['chk'] as $arrayKey => $key){
$appObj->cats[] = $key;
}
Try to use name="chk[]" in form control.
<input type="checkbox" name="chk[]" value="1"> 1<br />
<input type="checkbox" name="chk[]" value="2"> 2<br />
<input type="checkbox" name="chk[]" value="3"> 3<br />
And then check if you have an array.
if( !empty($_POST["chk"]) )
{
print_r($_POST["chk"]);
}
Running a foreach through $_POST is really not a crime and is probably the only way to do this.
If you are already appyling other logic why not put this all in the same foreach?
Also to save you some processing you don't need to pass strlen($key) as the 3rd paramater in substr just exclude that parameter completely and it will do the same thing.