<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";
}
Related
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);
I prepend
$('.VHere').prepend('<input type="checkbox" value="test1" id="testid">');
And write into the DB. When posting via form, the does not capture #testid. It capture every other field in the form except for this. Also if the page is reloaded this particular field is captured.
Any idea why.
We need to see more code, but there is no name associated with this input, which may be why the content is not being added to the DB.
I would think it would be
$('.VHere').
prepend('<input type="checkbox" name="testid" value="test1" id="testid">');
where testid populates the field
may be this works?
$('.VHere').prepend('<input type="checkbox" name="testid" checked="checked" value="test1" id="testid">');
because unchecked box cannot be submitted with post as AD7six says and name is of course important to post and catch back..
Only my checkboxes that are checked are being put into $_POST. I would like for the ones that are checked to be in $_POST with a value of 'true' and the non checked ones to have a value of 'false.' Is there anyway to do this or will the POST request always only contain info about checked checkboxes.
The only thing I can think of is to use hidden form fields and just have the checkboxes manipulate those.
See Posting Unchecked Checkbox and Unchecked checkbox values
It is possible by adding hidden fields with same name.
you can use
<input type="checkbox" name="myCheckbox" value="true" />
<input type="hidden" name="myCheckbox" value="false" />
and then parse the input on the server. You'll either get false or true false, the former maps to false and the latter maps to true
it will only contain content of checked checkboxes. you have to emulate that otherwise by using a form helper or an input filter that wires your variables / arrays the way you like it.
such functionality will need all checkboxes you use per form and can then set to true whats found and leave at false whats not detected.
It's not possible, since it's browser dependend.
You can just check if it's posted by doing
<?php
if (isset($_POST['checkbox1']))
{
// it's posted
}
Or use !:
<?php
if (!isset($_POST['checkbox1']))
{
// it's NOT posted
}
You can assume in your server-side that those who are not set on the post data, are unchecked. Try to verify if the variable is set:
$_POST['a_checkbox'] = (isset($_POST['a_checkbox'])) ? 1 : 0;
Use true and false, or data ase needed.
you could from your php do:
if(isset($_POST['checkbox'])||$_POST['checkbox']!="yes"){
//other code here
}
or, you could have some javascript to add a hidden input before submit for checkbox values that are not being sent
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).
what i want to do is that when you vote Y or N (two different radio buttons) and then it inserts into the "vote" column(in database) = Y or N(what you pickd), if nothing then echo error.
I know how to do this like halfway, i never worked with radiobuttons before so i need you guys.
Here's a two radio button right:
Yes: <input type="radio" value="Y" id="voteYes" name="vote"></input> <br>
No: <input type="radio" value="N" id="voteNo" name="vote"> </input>
I gave the value N and Y, not the same ID, but the same name. I think its right, but how should i do with the PHP part of what i want to do? I mean shall i call for "vote"? ($_GET["vote"]) i dont think so.. here's where im stuck
You're almost there. Depending on whether or not your form uses the GET or POST method, you'll have to change the variable name appropriately.
if(isset($_GET["vote"])) //checks to see if the user inputed something
{
$value = $_GET["vote"]; //remember, this value is not guaranteed to be either Y or N
}
else
{
//display your error
}
Why not? Just make sure you validate your data... make sure $_GET['vote'] must be an element of array('Y', 'N'), if true you insert it, else echo error and you're done.
POST variables are found in $_POST.
echo $_POST['vote'];
It depends on the method used. If you POST the form, then the variable will be $_POST['vote'], if you GET the form (default) then it will be $_GET['vote'].
Specify the method used in the form tag:
<form action="foo.php" method="POST">
or...
<form action="foo.php" method="GET">
Check for the existance of the variable either with isset() or array_key_exists().