Pass selected checkboxs between pages - php

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)

Related

Checkbox group add to database

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

How can I populate the fields of a PHP form automatically when the field values are in the url?

I have a have in PHP and I have common fields such as 'Name' and 'Surname'.
Now when the user visits the page e.g. http://www.example.com/form.php the form fields 'Name' and 'Surname' are empty.
I would like to now have a link similar to this http://www.example.com/form.php?name=John
so that when the client hits the link the PHP form will now have the name field already filled with 'John' in it.
I know this can be done in HTML but how can I do it in PHP?
Just to let to know I do not own the PHP form - I just want a link from my website to fill the PHP form (which I do not have control over).
Thanks in advance.
Can be done using $_GET
An associative array of variables passed to the current script via the URL parameters.
e.g.:
<? php
if(isset($_GET['name']))
{
$test = $_GET['name'];
}
?>
<html>
<body>
<form>
<input type="text" name="test" value="<?php if(isset($test)){echo "$test";}?>"/>
</form>
</body>
</html>
Note: code isnt tested or anything.. Also, there are possible security risks with getting values from your URL (can be considered user input), so make sure you are aware of that and how to prevent
You could store that value and then when you're about to output the input fields
you just pass along the stored value.
$name = $_GET['name'];
// ... later on
echo '<input type="text" value="'.$name.'"/>';
By using $_GET superglobal
<input name="name" value="<?php echo !empty($_GET['name']) ? $_GET['name'] : '';?>" />
<input name="surname" value="<?php echo !empty($_GET['surname']) ? $_GET['surname'] : '';?>" />
You can use the get method in php to get the name and make use of it
You can retrive this information by the $_GET["name"] function, or $_REQUEST["name"].
Reserver variables
Be carefull with those operations, you might have validation a/o security problem.
Note: if you are not sure that the "name" variable is set or not, you have to use also the
isset function to test it.
You can use the $_GET superglobal, so your input could look like this:
<input type="text" name="name" value="<?php if(isset($_GET['name'])) { echo $_GET['name']; } ?>" />
The $_REQUEST superglobal does a similar thing but I would just use $_GET.
It looks like everyone's answers here assume you are building the form yourself, which doesn't appear to be the case based on your question.
The thing that you want to do may or may not be possible. If the form accepts certain kinds of parameters in certain ways, you may be able to hook in to that functionality and set it up so that when someone clicks a link on your page, that information gets passed to the other page.
One way forms can accept this information is in the form of a "get" request. With this method, values are passed as part of the url, as in your example: http://www.example.com/form.php?name=John. Assuming your page has access to a php variable called $name, you can create a link from your code to build this kind of url like this:
Sign up!
If the page does not accept get parameters in this way (and I have a hard time imagining that they would), you may have to try other techniques to send along the information (assuming that they will even accept it!). The two other ways I imagine you could do this are by passing the value with "post" or creating a cookie for the page. If you tell us what page you are trying to set up this behavior on, we might be able to examine it and give you a better answer.

Update MySQL DB with PHP from Checkbox

I am pulling data down from a MySQL table and loading it into a form for editing(updating) a record. Everything is working great until I come the the check boxes. The checkboxes in the form accurately reflect the values in the appropriate columns in the db. But when the person editing changes the checkbox in the edit form it does not pass the data to the database. I have read a ton of checkbox Q&A on stack overflow but don't seem to find what I am looking for. Sorry if this is a redundant Question. Here is the code.
<label for="amenities-beach">
<input class="choose" name="amenitiesB" id="amenities-beach" type="checkbox"
value="<?php echo $row1["amenitiesB"]; ?>"
<?php echo $row1["amenitiesB"] ? 'checked="checked"' : ''; ?> />
Close to Beach</label>
Where amenitiesB in:
value="<?php echo $row1["amenitiesB"]; ?>
is what has been returned from the DB with a SELECT statement with:
$row1 = mysql_fetch_array($result);
But when I change the value in the form and submit it nothing is passed to the variable in the UPDATE statement. Any idea what I am missing? I have 6 of these checkboxes,amenitiesB, amenitiesK, amenitiesS, amenitiesP, amenitiesF, and preferred all with the same code. Any help would be appreciated.
Thank You,
Dave
Ok here is the code: Everything else in the form updates fine. I attempt to pass it to:
$amenitiesB = $_POST['amenitiesB'];
then I put it into the update statement
Hotels.amenitiesB='".$amenitiesB."',
My UPDATE statement is,
$query="UPDATE Hotels
JOIN surfcup_Rates ON Hotels.id = surfcup_Rates.hotelid
SET Hotels.hotel='".$hotel."',
More columns, then
Hotels.amenitiesB='".$amenitiesB."',
Hotels.amenitiesB='".$amenitiesK."',
Hotels.amenitiesB='".$amenitiesS."',
Hotels.amenitiesB='".$amenitiesP."',
Hotels.amenitiesB='".$amenitiesF."',
Hotels.amenitiesB='".$preferred."',
More columns then:
WHERE Hotels.id='".$id."'";
The problem you have comes because when a checkbox is unchecked, by default its data is not transmitted to your PHP, and that's why you have problems by having the UPDATE query parameter empty.
So before your update statement you should have:
$fieldenabled=(bool)(isset($_POST['CHECKBOXNAME']) ? TRUE : FALSE;
And call your UPDATE query with that.
EDIT: Of course you can change $_POST with $_GET depending on the sending method of the <form>
Edit: I think I get the problem. When the box is initially unchecked, the input has an empty value, then when you check it, it passes an empty value in... it will never fill with what you intend the checked value to be. So, instead you need something like this:
<input class="choose" name="amenitiesB" id="amenities-beach" type="checkbox" value="amenity B Selected" <?php echo $row1["amenitiesB"] ? 'checked="checked"' : ''; ?> />
... don't make the "value" attribute dynamic, or else once it becomes empty it will always be empty.
Original Answer:
I assume when you say "change the value in the form" you mean that you uncheck the checkbox... unchecked checkboxes never send any data when you submit the form. You check for "unchecked" status by checking to see if the form variable has been passed at all.
For example:
if (isset($_GET['amenitiesB'])) {
// process with the knowledge that "amenitiesB" was checked
}
else {
// process with the knowledge that "amenitiesB" was unchecked
}
If you mean that you somehow dynamically change the "value" of the checkbox to something else, then I'll need to see the code that accomplishes that.
The main purpose of the "value" attribute in a checkbox input is when you're passing the variable as an array:
<label for="amenities-beach">
<input class="choose" name="amenities[]" id="amenities-beach" type="checkbox" value="<?php echo $row1["amenitiesB"]; ?>" <?php echo $row1["amenitiesB"] ? 'checked="checked"' : ''; ?> />
Close to Beach
</label>
... note specifically that I've changed the "name" attribute from "amenitiesB" to "amenities[]", which, if carried through all of your amenities checkboxes, will give you access to them all in your processing script through the $_GET['amenities'] array (or $_POST, if applicable). Otherwise, there's not much reason to use the "value" attribute of the checkbox input, because you can get all you need just by knowing $_GET['amenitiesB'] is checked (and thus sent with the form) or unchecked (and not sent with the form).

Checkbox and search query in Codeigniter

My page is coded in PHP/codeigniter and I have a form with some checkboxes in it. When I select a few checkboxes and submit the form, I pass the checkbox values to the controller, which then decides if a checkbox is checked, implodes all the checked checkbox values into an array and passes to the url using uri->assoc_to_uri($array). This is how I coded my filters for a search engine (any better way?). Now when I redisplay the form with the checkboxes again, I want the checkboxes previously checked to be checked again. How can I do this?
My initial idea is to do a uri_>uri_to_assoc(#), find the value of the relevant key (ie. 1.2.3) then explode to an array $arr and something like the following code:
<input type="checkbox" name="price_range_4" value="<?php if($arr[4] != '') echo 'selected'; ?>">
Is there a faster/better way?
Why not use the Session Class and pass an array to set_flashdata(), then retrieve it on the search results page to check the checkboxes?
In addition to Darren's answer you have another HTML problem:
<input type="checkbox" name="price_range_4" value="<?php if($arr[4] != '') echo 'selected'; ?>">
It's not the value you want to change, it's the checked attribute. Something like this:
<input type="checkbox" name="price_range_4" value="my_value"<?php if ($should_be_checked) echo ' checked="checked"'; ?> />
If you're using the Form helper, you can use the form_checkbox() function to make this a bit cleaner:
Example:
echo form_checkbox('price_range_4', 'my_value', $should_be_checked);
Of course $should_be_checked will be whatever way you decide to define it, either with session data, $_POST data, or another way.

Using javascript and $_SESSION's to record wanted user information over pagination

What I have so far is a paginated page, showing all users in a database system. Each page shows 30 users and has a checkbox next to each user, what I need is a way for users to select and deselect these users and for these selections to propagate through, so if the user goes back to page 1 from page 2, all users from page 1 will still be checked.
I also need a way to record this information, so that once the user has looked at all the pages and clicks a submit form all checked users information can be processed. I am thinking of using javascript to record the information and php sessions to store it, but with the way I am trying now, when a user clicks a checkbox, it is not ticked.
Does anyone have a better way of doing this/see how I can fix this problem?
Thanks.
<script type="text/javascript">
function log_export($str) {
document.check.data.value = $str;
document.check.submit();
}
</script>
<?php
if(isset($_POST['data'])) {
echo $_POST['data'];
}
?>
<form name="check" method = "post" action = "">
<input type="hidden" name="data">
<input type="checkbox" name="A" onclick="log_export('1')" />
<input type="checkbox" name="B" onclick="log_export('2')" />
<input type="checkbox" name="C" onclick="log_export('3')" />
</form>
Few ways you could do this, but I'd avoid using javascript to do it. You could use an array in your $_SESSION to keep the list across pages.
<form name="check" method = "post" action = "">
<input type="checkbox" name="person[A]" />
</form>
(note: The form elements are named person[A], person[B]...etc, so they can be accessed as an array in php and make your life easier.)
Then in the php you can store this in the session...
$_SESSION['saved_list'] = $_REQUEST['person'];
This way the session variable saved_list will contain the array person with all the checked boxes in it. You'll need to be careful not to overwrite the array each time however, so adding...
$_REQUEST['person'] = array_merge($_SESSION['saved_list'], $_REQUEST['person']);
...before this should keep them (if I'm remembering my merge functions correctly).
Alternatively, you could just use html to save the checkboxes already ticked. When page 2 receives the results from page 1, it could print them out as hidden elements at the end of the page 2 form. This way they can exist across pages, however this could become a bit unwieldy with 30 names a page.
I'd suggest storing it in a php session array, this shouldnt really involve using Javascript, it just over-complicates matters.
Why you don't change your form method to GET and make the pagination link so it contains every parameters passed to the form and the page number. I think it make everything more simple to handle that case with parameters passed on the URL against posted one.
you can create those links like this:
for ($i =0; $i < $max_page; $i++){
echo "{$_SERVER['REQUEST_URI']}?$_SERVER['QUERY_STRING']&p={$i}";
and you just have to change your backend to use $_GET instead of $_POST.

Categories