php checkboxes always showing checked - php

I've got a single checkbox which i'd like the unchecked value to be 0 and the checked value to be 1, but when the post goes through, it always shows as 1 whether the box is checked or not..
Here's the checkbox:
<input name="stock[]" type="checkbox" id="stock[]"> value="1" />
here's what it spits out regardless of whether it's checked or not.. (there are multiple "stock" checkboxes..
[stock] => Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => 1
[5] => 1
)
I can't seem to get it working.. :S Any ideas? :)

It seems like you have a extra > in your Checkbox HTML. Value is not used in case of checkboxes.
<input name="stock[]" type="checkbox" />
because you have value="1", the form will always submit the value regardless of whether checked or not. So remove the value attribute will help.
And to preset the checkbox to be checked, use the checked attribute instead. Example:
<input name="stock[]" type="checkbox" checked="checked" />

(Obviously, you need to start by removing that extraneous > sign.)
Checkboxes and radio buttons must have a value attribute. If they're checked, that value is sent when the form is submitted; if they're not checked, no value is submitted. Thus, you can't directly do the "0 if unchecked, 1 if checked" thing. What you can do instead is use the value attribute to detect which checkboxes were checked.
<input type="checkbox" name="stock[]" value="1" id="stock1" />
<input type="checkbox" name="stock[]" value="2" id="stock2" />
<input type="checkbox" name="stock[]" value="3" id="stock3" />
If the 1st and 3rd boxes are checked, but the 2nd is not, then when you look at the value of the stock[] array in your code, you'll find that it contains 1 and 3, but not 2.
Edit: I just confirmed that the reason it looked like all of your checkboxes had values submitted was that you failed to give the form any way to differentiate among them. If you have multiple checkboxes with not only the same name but the same value, then your form results will look something like "stock[] = 1, stock[] = 1, stock[] = 1". PHP will then interpret this as stock[1] = 1, stock[2] = 1, etc., but the point is that stock[2] might actually be the fourth checkbox - neither the form nor php has any way to tell where each value came from.
So bottomline is, you can either use the same name for a series of checkboxes, OR you can use the same value, but not both at once: if you use the same name, you have to use the value to differentiate among the controls; and vice versa, if you want to use the same value, you need to use different names.
By the way, if you don't specify the value of a checkbox, then most browsers will supply a default value of their own - for example, IE and Firefox use "on" (or "ON" in some versions). But depending on such defaults is always a bad idea.

I'm not sure you can/should name an input element "stock[]" - try getting rid of the [] and re-test.

Related

Is the html sending null or empty?

I have some cases here.
A pair of radio buttons:
<input type="radio" id="One" name="MyRadio" value="">
<input type="radio" id="Two" name="MyRadio">
So I have 3 scenarios.
I select "One"
I select "Two"
I select none and I send the form.
And a similar case with select
<option value=''>Three</option>
<option>Four</option>
My questions are
a) What will be send in cases 1,2 and 3 (and 4, 5 and 6)?
b) In case I need to check the values, should I use isset() or empty() when reciving them in the next script?
With the first radio, this would be an empty string. With the second radio, this wouldn't be in the POST data. You can test both with empty().
To confuse matters, the option without a value would have the text send to the server so 'Four' where as an empty string would be sent for Three.
However, this is from memory. What you can do is paste $_POST into var_dump() to check the results yourself :)

PHP submitting form with a variable amount of fields with variable names, check if at least one set

Okay so my title might be a little confusing, but let me explain my situation:
I have a pretty big form with lots of fields, some which are required, some which are not. I do validation with JS, but then I'm also doing validation on the server side with PHP.
One of the things I'm asking the user for is a "Header Name". Now, header name has the name attribute of "header1". The user has the option of adding more header fields on the form. So if they click a button it adds another "Header Name X" with name attribute "headerx".
Got it? Now, the problem is, in general these header fields are not required, but I do have the condition that they MUST supply at least one Header field. So they could supply 100, they could supply 2, they might supply 1, but if they don't supply any then validation should fail.
I can't think of a good way of checking for this in PHP though. I know your fist thought is just check if $_POST contains anything. Won't work though because they are multiple other fields in this form that are required that have nothing to do with these Headers. So I can't just simply check to see if $_POST contains something because it always will.
Is there a way I can like combine isset() with a regular expression? Like isset($_POST['header{\d+}']. Which would be saying like header with atleast one digit following it.
Thanks for the help!
EDIT: Oh and if this wasn't hard enough already, the amount of Header Fields is limitless. So I can't just loop through all the possible "headerx" because that would obviously be an infinite loop.
You could have field names with []:
<input type="text" name="foo[]" value="x" />
<input type="text" name="foo[]" value="y" />
Then $_POST would be like:
array('foo' => array('x', 'y'));
You could even have associative arrays:
<input type="text" name="foo[bar][first]" value="x" />
<input type="text" name="foo[bar][second]" value="y" />
Would look like:
array('foo' => array('bar' => array('first' => 'x', 'second' => 'y')))
You can loop through the elements like this:
$i = 1;
while($row = $_POST['header' . $i++]){
//do stuff
}
this will keep going until there are no more sequential elements.
Why not simply look at it this way: In your JS on the other end, when you are doing validation, have the last check a check to verify that a header is sent - and it it passes, set a hidden field in the form to a true value - then in your PHP you can check that particular element without having to worry about every possible header that is sent.
if(!count(preg_grep('#^header\d+$#',array_keys($_POST))))
{
//no header submitted
}
This will allow to use a RegExp as requested, but I also would prefer the solution by jpic

changing boolean values in php

I have a bunch of values from checkboxes that are boolean. Al I want to do is set them to yes if they are 1 and no if they are 0.
My code fails, looks ok to me?
$item = $form_state['values']['item1'] == 1 ? 'Yes' : 'No';
If your checkboxes have value attribute equal to 1, it should be OK:
<input ... type="checkbox" value="1" />
If you have not set these values or in all the cases you may just check, if they exists in $_GET or $_POST array (assuming $form_state is taken from there):
$item = isset($form_state['values']['item1']) ? 'Yes' : 'No';
The above example, should works for you. Keep in mind radio buttons and check boxes will not be set in $_GET or $_POST if they are not selected, at all, which also may generate Notice or Warning, if trying to access non-existing index.
In older versions of php you might need to use $_REQUEST.

Passing method, html/php

If i have 3 checkboxes that you can check for the transport available: Taxi, Train, Bus.. how should i pass them in a nice way? Cant you like pass a array with Transport = bus, train (those you checked), or maybe you have to send them seperatly one variable at a time, because it is inside a form (and already are a array all of it)?
I assume you are talking about sending the data from the client to the server. If so, you can give the checkboxes the same name:
<input type="checkbox" name="transport[]" value="Taxi"> Taxi <br />
<input type="checkbox" name="transport[]" value="Train"> Train <br />
<input type="checkbox" name="transport[]" value="Bus"> Bus <br />
When you sent the form, the data will be available as array in $_POST['transport'] (or $_GET, depending on which methods you use). The [] in the input field name will make PHP parse the data as array.
More information in Variables From External Sources.
Some more explanation:
Without the brackets (i.e. []), the resulting query string would look like this (assuming Taxi and Train are selected):
transport=Taxi&transport=Train
PHP, in contrast to other languages, will only consider the last value for the same key. In order to make PHP treat values with the same key as array, you have to append [] to the name.
All input fields will be passed as part of your $_POST or $_GET arrays, based on the method type of your form submission. Checkboxes are passed as name=on or name= whether the checkboxes are selected or not. Depending on how you're processing the submitted form data there are different ways to work with the values. I hope this helps?
If you use something like this:
<input type="checkbox" name="transport[]" value="bus" />
<input type="checkbox" name="transport[]" value="train" />
<input type="checkbox" name="transport[]" value="taxi" />
The values will be passed as an array accessible with $_POST['transport']. If the user checks the first and the last checkboxes $_POST['transport'] will contain two strings: 0 => "bus", 1 => "taxi".
Also see http://jetlogs.org/2007/07/19/passing-input-arrays-in-php/.

Codeigniter unchecked checkbox value = blank?

I have this database where I have to capture a lot of yes/no questions, and the prefered method for the users is checkboxes. Everything is working as it should, except when it comes to retreive and show the values. Unchecked boxes return values of "0"
Is there anyway to either ignore and not display "0" in the reports OR change the default value from "0" to blank"
result = $this->input->post('checkbox',TRUE)==null ? 0 : 1
this is nothing to do with CodeIgniter. :)
How about this?
if($_POST['checkbox']==0)
$_POST['checkbox'] = '';
It is returning 0 because that is false and that's what check boxes returned when not checked. Just add an if in your CI processing method that returns whatever value you want if the checkbox value==0.
Edit: Just to clarify, this doesn't have anything to do with your CI. What I mean by it is returning 0 is that that is what the form itself is returning - that the behavior of a checkbox. To change the value will take a quick check in your CI code to change the 0 to a value you want. I assume you are accessing the value somewhere to create your email.
since the the checkbox returning null value while unchecked, you won't get a value while posting. Here is a simple quick solution for returning unchecked value from checkbox,
<input type="hidden" name="cbox" value="0" />
<input type="checkbox" name="cbox" value="1" />
if( ! $_POST['checkbox']) $_POST['checkbox'] = '';
If a checkbox is not checked, no data is sent for it. (If it is checked, the value attribute is sent). Attempting to read $_POST['checkbox'] will cause a PHP error (unless you use empty() or isset(), which are special language constructs).
this->input->post('checkbox') will return FALSE if the checkbox data is not set, i.e. if it was not checked. There's no way to change that value, I'm afraid. If you want a different value, you will need to manually compare FALSE and use a different value.
Finally, when you submit FALSE to the database using CodeIgniter's DB access API, it is converted to '0'. This would work well for a boolean column in the database. When you read out a boolean column, you'll get whatever your database's preferred code for TRUE is, regardless of what you submitted originally. (With the possible exception of sqlite, which is weakly-typed, a bit like PHP is).

Categories