Checkbox group add to database - php

I have the following query that retrieves client data to create a checkbox group. I need to add the selected checkboxes to a database as individual rows, but I am not sure how to write this as I have not done it before. I'm confused because the number of checkboxes will vary in number.
res=mysql_query('SELECT id,name FROM tbl_client WHERE active="1" ORDER BY name DESC',$dbh) or die(mysql_error());
num=mysql_num_rows($res);
for($run=0; $run<$num; $run++)
{
val=mysql_fetch_row($res);
echo '<label><input type="checkbox" name="CheckboxGroup1" value="'.$val[0].'" id="CheckboxGroup1_0" />'.$val[1].'</label><br />';
}
How do I access the checkboxes in order to add them to individual rows in a database when I submit them? I guess I could use some kind of Foreach statement, I just have no idea how to do it.

What you need is to use an array, which means naming your input fields with trailing opening [ and closing square brackets ] like so...
<label><input type="checkbox" name="CheckboxGroup[]" /></label><br />
What this does is create an array named CheckboxGroup in your $_POST or $_GET super globals (depending on which method the form uses), when the form is submitted to your PHP script. So if you had 1 or 1000 of these input elements in your HTML they will all populate under $_POST['CheckboxGroup'] -- or $_GET -- in PHP and you can iterate over them like this...
foreach ($_POST['CheckboxGroup'] as $checkbox) {
/* do whatever you want with $checkbox here */
}
Please note that a checkbox value is only sent in the request by the UA if it is checked. Also please don't use mysql_* functions to interface with your mysql database in PHP as it is deprecated and will be removed from future versions of PHP. For new applications please consider using either MySQLi or PDO to interface with your mysql database in PHP.

In HTML forms, the checkbox and radio controls are unique in that they are not present in the request if they are not fired by the client. So your script has to know in advance what checkboxes to expect. With inputs of type=text, submit, etc., the request contains the named control, even if the data string is empty.
There are several ways to accomplish this sort of thing. You can make arrays of checkboxes, with or without named elements, like this:'
<input type="checkbox" name="color[orange]" />Orange
<input type="checkbox" name="color[green]" />Green
You can also provide type=hidden form elements with the same names as the checkbox elements. The last form element of the same name is the one that will be presented with the request. By doing this you can always have a predictable number of elements. The hidden value will be in the request if the checkbox is not fired. The checkbox value will be there if the client selected the checkbox.
Try setting up a form that submits your checkbox tests to a PHP script that says this (shown here in its entirety)
<?php var_dump($_POST);

Related

using php post without having the tag name

I need something very simple.
I have different html pages (in total eleven) with forms that when submitted they will send via post the values of an input form.
These pages are very different, with inputs tags with different names and functions ecc...
The php must save data inside a pre-existed excel file so i pass to my php page also the cell where save the data.
But because there are very different pages with different tag names, i want only to write a php file that use the $_POST array using numeric index instead of the name of the tag as key. That's possibile?
An example of part of a form of one of the all pages is this
Client name <input type="text" name="client_name"/> <input type="hidden" value="A8">
An esample of a second page could be
Address of you friend <input type="text" name="address"/> <input type="hidden" value="A1"> <br>
<br>
When one of these send via the submit button using method post, the content in $_POST[1] will be A8 if the php page is called from the first html page and will be A1 if the php page is called from the second html page?
Form controls without names cannot be successful controls.
Only data from successful controls is sent to the server in the HTTP request.
Since your controls don't have names, they won't be in the data, so the server will never get the data. It can't pass the data to PHP and PHP can't use it to populate to $_POST.
If they had names, but you didn't know what they were, then you could loop over the keys of the $_POST array like any other associative array.
foreach ($_POST as $key => $value) {
echo htmlspecialchars($key);
}

Combine multiple forms $_GET values into query string

So, i have 2 forms to filter products, one with checkboxes and the other with select options.
When i check one checkbox the form is submited and the query string is updated with it's value, when i check another checkbox the same happens, but when i select a option, the current query string resets and add only that option value instead of adding it after or before the current query.
What i want is to unite both $_GET indexes in the query string, independent of the order of submit. How can i do this? I'll be grateful if someone knows.
$marca_get = isset($_GET['marca']) && is_array($_GET['marca'])
? $_GET['marca'] : [];
if ( isset($_GET['ordem']) ) {
if ( $_GET['ordem'] == 'vendas' ) {
$orderby = 'vendas';
}
if ( $_GET['ordem'] == 'avaliacoes' ) {
$orderby = 'avaliacoes';
}
}
<form method="get">
<input type="checkbox" id="amd" class="checkbox-filtro" name="marca[]"
value="amd">
<label for="amd">AMD</label>
<input type="checkbox" id="intel" class="checkbox-filtro" name="marca[]"
value="intel">
<label for="intel">Intel</label>
</form>
<form method="get">
<select id="ordem" name="ordem">
<option value="vendas">Mais vendidos</option>
<option value="avaliacoes">Melhor avaliados</option>
</select>
</form>
$('#ordem, .checkbox-filtro').on('change', function() {
this.form.submit();
});
Quotes from Mozilla Developer Network:
The HTML <form> element represents a document section that
contains interactive controls for submitting information to a web
server.
When a form uses the get method, the fields are put into the URL Query String:
get: Corresponds to the HTTP GET method; form data are appended to the action attribute URI with a '?' as separator, and the resulting URI is sent to the server.
Your page has two forms, which is OK if they are unrelated. For example a page with a search form in the header, and a comment form at the bottom, would have separate forms because they do different things. The search form is also likely to have a different action URL than the comment form.
Option 1
The easiest way to get two forms to share state, is to just use one form instead of two.
If you want two forms to be united, and they also share the same action URL, this indicates that they are basically the same form.
The form element groups the fields that belong to a particular action.
The default style of a form element means users cannot see the form's boundary, and a form element can contain other 'non-form' content, just like a form on paper would.
Option 2
Copy the other form's fields, but make them hidden.
<input type="hidden" name="ordem" value="<?php echo $_GET['ordem']; ?>">
Suppose your visual design has exposed a form's boundary (CSS border or background). It may not be visually desirable to contain a significant amount of content.
This is slightly more maintenance. It may be worth redesigning the HTML/CSS so the form element is not styled directly.

How can I group radio together and still pass them through $_POST as an array?

Short Version:
I know how to pass input values as an array as well as how to delineate between different groups of radio buttons, but I'm not sure how to do it together because I use the name property to do both.
Long Version:
I want to pass a bunch of selections to a PHP backend. Using basic HTML, a group of inputs can be passed as a single array. I do this with the name attribute:
<input type="checkbox" name="choices[]">
This is good because I can simply go down the list of choices and deal with whatever is in the array instead of checking for a myriad of different names of inputs that were possibly selected.
We also use basic HTML to group radio buttons together. So we can have a group of radio buttons for "Male/Female" as well as "Old Member/New Member" and not have them conflict (meaning, you can only choose either either male or female as well as either new/old member…the page doesn't force a single choice out of all 4 of those). I do this with the name attribute:
<input type="radio" name="sex">Male
<input type="radio" name="sex">Female
<input type="radio" name="membership">Old Member
<input type="radio" name="membership">New Member
So my issue is, how do I do both at once? I need to have separate 'groups' of radio buttons, but still want to pass everything as an array, but the problem is I use the name attribute for both! If I name it the array-name, I can't differentiate between the radio-groups. If I differentiate, I lose the array…
You can set array in action page,
in PHP
<?php
$join = array($_POST['sex'],$_POST['membership']);
?>
And you can process based on above array
So the approach I ended up using was to look through $_POST for arrays and then merge them. (Obviously, this only works if you know that the only arrays in $_POST are of the type you need…). This is, roughly, my PHP:
$firstElem = true;
foreach ($_POST as $element){
if( is_array($element) ){
if($firstElem){
$firstElem = false;
$members = $element;
}else{
$members = array_merge($members, $element);
}
}
}

Pass selected checkboxs between pages

I want to pass the values of selected checkboxs between pages. How can I do this ? I think that I have to use JavaScript to get select checkbox values but I don't know how pass to another page the values.
Best Regards
It depends on on which side you want to preserve them. On client side? If so, use session. On clien side? Then use any local storage, like jStorage, HTML5 Storage, DOM Storage etc...
The simplest way would be to use a PHP session:
<?php
//start session
session_start();
//get the posted values from your form
$_SESSION['checkbox_value_1'] = $_POST['checkbox_1_name'];
$_SESSION['checkbox_value_2'] = $_POST['checkbox_2_name'];
$_SESSION['checkbox_value_3'] = $_POST['checkbox_3_name'];
?>
So, when you need the values of the checkboxes you can can get the from the session:
<input type="checkbox" value="<?php echo $_SESSION['checkbox_value_1'] ?>" name="checkbox_1" />
That should do it.
You can also set the checkbox to 'checked' if you add this bit:
<?php
if (isset($_SESSION['checkbox_value_1']) && $_SESSION['checkbox_value_1'] != ''){
//is selected (has a value)
$checkbox_selected = 'checked="checked"';
} else $checkbox_selected = ''; //not checked
?>
Then you can write your checkbox like so:
<input type="checkbox" value="<?php echo $_SESSION['checkbox_value_1'] ?>" name="checkbox_1" <?php echo $checkbox_selected; ?> />
This will add the checked="checked" attribute to the checkbox.
You could also store these in an array if you want to limit the number of session values. Let me know if you'd like an example of that.
you could add get parameter to the form as you post it (so it sets get parameters to the url) representing the checkboxes and then using php to print checked and unchecked boxes according to the last states
for this you would have to catch the submit event of your form via javascript, parse the values of your form's boxes into get-values (many javascript frameworks have support for such operations) and then finally post it to the server, the php on the server then uses the global $_GET variable to test each state when printing the boxes.
(this is a rough idea of an implementation, allways consider unvalidated user parameters could be harmfull for your application)

Passing checkbox state to PHP

<input type="hidden" name="check_box_1" value="0" />
<input type="checkbox" name="check_box_1" value="1" />
This works fine, however when you click on submit, and the checkbox is ticked, it passes BOTH the hidden value and the original checkbox value to the $_POST variable in php, can this be avoided?
I have the hidden value there, so that unticked checkboxes are passed to the $_POST variable as well as the ticked ones.
The better approach is to remove the hidden field, and simply have a check in PHP:
if ($_POST['check_box_1']=='1') { /*Do something for ticked*/ }
else { /*Do something for unticked*/ }
You shouldn't need the hidden field. You should in fact not trust any of the form fields sent in the first place. What this means is that you cannot make code which takes the sent fields and trust them to send the correct data (which I assume you do now).
What you should do is to handle all fields you expect to get. That way if you don't get the checkbox value you can still handle that as if it was unticked. Then you also get the added inherent feature of throwing away form data you don't expect in the first place.
No, it will pass all the form data, whatever it is. The right way to do this is not to set the checkbox via a hidden field but to set the checkbox with whatever its state actually is!
I mean... why are you adding the hidden field to begin with?
Your PHP is receiving two fields named check_box_1, and last time I checked there was no way to guarantee that the params would get read into the REQUEST hash in the exact same order as you sent them, so, there's no way to tell which one will arrive last (that's the one whose value will get set). So... this is not the right approach to whatever problem you're trying to solve here.
Welcome to Stack, btw! If you find answers useful or helpful, make sure to mark them as correct and vote them up.
That's normal.
They must be both type="checkbox" to pass only 1 value.
If you want to get only 1 in any cases you can do:
<input type="checkbox" style="display:none;" name="check_box_1" value="0">
Make sure the first input field is of type Checkbox, or else it won't behave like one.
<input type="checkbox" name="check_box_0" value="0" />
<input type="checkbox" name="check_box_1" value="1" />
Everything is working normal with your code so far.
I'm assuming you are creating the hidden field so that 0 is passed to the server when the checkbox is not checked. The problem is that they both get passed when the check box is checked.
As Death said, the way you should be doing it is with a single checkbox and then checking if the value has been sent to the server or not. That's just how checkboxes work.
If you want to have a default set then you will have to handle all that on the server side based on weather the checkbox has a value.
For example:
$myValue = "";
if(isset($_POST['check_box_1']))
{
$myValue=$_POST['check_box_1'];
}
else
{
$myValue="0";
}

Categories