I'm confused by what counts as empty in this code logic. I have a variable amount of table rows (additional rows are dynamically inserted via ajax) that each accept four inputs. The logic I want is for a particular row - whose inputs are incomplete - to be unable to update a database:
if ((isset($_POST['_branch']) && !empty($_POST['_branch']))
&& (isset($_POST['_day']) && !empty($_POST['_day']))
&& (isset($_POST['_starttimepicker']) && !empty($_POST['_starttimepicker']))
&& (isset($_POST['_endtimepicker']) && !empty($_POST['_endtimepicker']))) {
$b_id = $_POST['_branch'];
$w_date = $_POST['_day'];
$s_time = $_POST['_starttimepicker'];
$e_time = $_POST['_endtimepicker'];
// ... rest of code comes here
}
The code snippet where the four inputs are handled:
<td>
<input class="form-control" type="text" id="_starttimepicker" name="_starttimepicker[]" placeholder="Enter Time" />
</td>
<td>
<input class="form-control" type="text" id="_endtimepicker" name="_endtimepicker[]" placeholder="Enter Time" />
</td>
When I have start time and end time "empty" (haven't interacted with them; the placeholder remains as "Enter Time"), the if-condition logic above still processes and the database is ultimately updated (with bad values). Even when I try to play around with the default value parameter (I have value = "" and "red"):
<td>
<input class="form-control" type="text" id="_starttimepicker" name="_starttimepicker[]" value="" placeholder="Enter Time" />
</td>
<td>
<input class="form-control" type="text" id="_endtimepicker" name="_endtimepicker[]" value="red" placeholder="Enter Time" />
</td>
The if logic still processes (also, the relevant database value where I had value="red" remains as "". I thought it would have taken the default value "red", so maybe I'm misunderstanding this).
What am I misunderstanding? Any advice?
I see that you use input arrays. To check empty form fields that are input arrays, you need more complicate than just empty().
Example HTML form:
<form method="post">
<input class="form-control" type="text" id="_starttimepicker" name="_starttimepicker[]" placeholder="Enter Time" />
<input class="form-control" type="text" id="_endtimepicker" name="_endtimepicker[]" placeholder="Enter Time" />
<button type="submit">Submit</button>
</form>
Here is PHP function to check it and how to use.
$_starttimepicker = ($_POST['_starttimepicker'] ?? []);
// in PHP older than 7.0 use (isset($_POST['_starttimepicker']) ? $_POST['_starttimepicker'] : []) instead.
$_endtimepicker = ($_POST['_endtimepicker'] ?? []);
/**
* Check if ANY fields are empty.
*
* #param array $fields The input form field, one by one.
* #return bool Return `true` if one of a form field is empty. Return `false` for otherwise.
*/
function isEmptyFields(...$fields)
{
$foundEmpty = false;
foreach ($fields as $field) {
if (is_array($field) && !empty($field)) {
foreach ($field as $index => $value) {
if (empty($value)) {
$foundEmpty = true;
break;
}
}
} else {
if (empty($field)) {
$foundEmpty = true;
break;
}
}
}
return $foundEmpty;
}
if (!isEmptyFields($_starttimepicker, $_endtimepicker)) {
// if all fields are NOT empty.
echo 'save your data.';
}
Tested submit the form by filled all fields, the result is in condition (save your data.) but if empty just one, it will not goes into if condition.
if($uriarray['value'] == 0 ){
I have an input form which includes values. The values are in a checkbox. I want to show something if it's the only value, but not if it's included with other values. So if the value is 0 I want to show something but if it includes other values like 1,2,3 etc, I don't want to show it. Is this something that's possible?
If & only if?
It depends on your HTML form. For example, if you specify the names of the checkboxes in array-form like:
<input type="checkbox" name="uriarray[]" value="0" />
<input type="checkbox" name="uriarray[]" value="1" />
<input type="checkbox" name="uriarray[]" value="2" />
<input type="checkbox" name="uriarray[]" value="3" />
you would receive an array in PHP with all checked values.
<?
if (count($_POST['uriarray']) == 1) {
$onlyValues = $_POST['uriarray'][0];
}
?>
If you also want to check the single value to be 0:
<?
if ((count($_POST['uriarray']) == 1) && ($_POST['uriarray'][0] == "0")) {
//Do something
}
?>
I am creating an HTML form and I have a textbox in that. My requirement is that a user can check multiple check boxes, and then I have to get all checked values and then send the values to the database (I want to use PHP).
Here is my code for within the textbox
$Intensive=$_POST['Intensive'];
$Intensive_count=count($Intensive);
$i=0;
//$count=0;
//$index;
$max=0;
//$index;
While($i < $Intensive_count)
{
if($Intensive[$i]=="High frequency ventilation" )
{
$Intensive_score=4;
}
elseif($Intensive[$i]=="Mechanical ventilation with muscle relaxation")
{
$Intensive_score=4;
}
elseif($Intensive[$i]=="Mechanical ventilation")
{
$Intensive_score=3;
}
elseif($Intensive[$i]=="CPAP")
{
$Intensive_score=2;
}
elseif($Intensive[$i]=="supplemental oxygen")
{
$Intensive_score=1;
}
if($Intensive_score>$max)
{
$max=$Intensive_score;
$index=$i;
}
$i++;
}
Now with the above code I am able to echo the value ,but the record is not going to the database.
$sql1="insert into Form2 values('$Medical_Record_Id','$sub1','$Question1','4','$Intensive[$index]','$max')";
mysql_query($sql1);
Could anybody tell me how to go about it.
Thanks ..:)
Assuming you are using POST as the method for sending the form those checkboxes are in, you can get the values array with $_POST['Intensive'].
I would recommend you use integers for the value instead of long strings, also an ID is supposed to be unique, so modify your ids.
HTML:
<input type="checkbox" name="Intensive[]" id="r1" value="1">supplemental oxygen<br>
<input type="checkbox" name="Intensive[]" id ="r2" value="2">supplemental oxygen<br>
<input type="checkbox" name="Intensive[]" id="r3" value="3">Mechanical ventilation<br>
<input type="checkbox" name="Intensive[]" id="r4" value="4">Mechanical ventilation with muscle relaxation<br>
<input type="checkbox" name="Intensive[]" id="r5" value="5">High-frequency ventilation
PHP:
foreach($_POST['Intensive'] as $data) {// Or $_GET
if ($data == 1){
/// do so and so
}
if ($data == 2){
/// do so and so
}
... and so on.
}
hello i have the following problem:
i would like to create a filter for a search engine. i have some inputfields for specific search terms and beside a respective checkbox. so that looks like:
inputfield a: [_____] filter for a: on/off: [ ]
inputfield b: [_____] filter for b: on/off: [ ]
inputfield c: [_____] filter for c: on/off: [ ]
the code structure of that is:
first of all check if the inputfield is empty and the checkbox is set checked. in case of checked it will be unchecked after submit. the other way around, if just the inputfield is filled and the checkbox unchecked, it also will error out, that there is a mistake and the filter can't work. so i'm using for each filter an own error array like (the name and value of the first checkbox is name="filter_a" value="1") :
...
$checkbox_filter_a = $db->real_escape_string(htmlentities(trim($_POST['filter_a'])));
...
$filter_a = (!empty($checkbox_filter_a)) ? 1 : 0;
...
$errors_a = array();
if ($filter_a == 1){
if (empty($input_a)){
$errors_a[] = 'the filter needs some input';
}
}
if (!empty($input_a)){
if ($filter_a == 0){
$errors_a[] = 'filter is not activated';
}
}
if there is no error and both criteria are fulfilled the filter either is on or not.
so the logical behind that is, when loading the page the checkbox have to be unchecked. after regarding the criteria to filter it is on.
to display the status checked or unchecked under the conditions below it should be checked after submit or either not. therefor i have this code for each filter (respective checkbox_filter_b, ...) the part of the checkbox after the inputfield:
<?php
if (checkbox_filter_a == 0 ) {
echo '<input type="checkbox" name="checkbox_filter_a" value="1" checked/>';
}else {
echo '<input type="checkbox" name="checkbox_filter_a" value="1"/>';
}
?>
what does not satisfy at all. this is because of the following problem:
when loading the page it will show all checkboxes are unchecked. if i try to cause an error because of no filled input or just checked checkbox for one of these filters, after submit all other checkboxes are automatically checked.
so if there is someone who could help me out i really would appreciate. thanks a lot.
Perhaps you could do it this way, by defining default values for your check boxes and values at the start of your script. Then change them with the values of the POSTed if there set or not.
<?php
//Setup Variable Defaults, if POST dont change them then there no complicated ifelse's
$filter_a=null;
$checkbox_filter_a='<input type="checkbox" name="checkbox_filter_a" value="1"/>';
$filter_b=null;
$checkbox_filter_b='<input type="checkbox" name="checkbox_filter_b" value="1"/>';
$filter_c=null;
$checkbox_filter_c='<input type="checkbox" name="checkbox_filter_c" value="1"/>';
//Check for post
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//If the check box is not checked checkbox_filter_a will fail this part
// so $filter_a will still be null
if(isset($_POST['filter_a']) && isset($_POST['checkbox_filter_a'])){
$filter_a = trim($_POST['filter_a']);
$checkbox_filter_a ='<input type="checkbox" name="checkbox_filter_a" value="1" checked/>';
}
if(isset($_POST['filter_b']) && isset($_POST['checkbox_filter_b'])){
$filter_b = trim($_POST['filter_b']);
$checkbox_filter_b = '<input type="checkbox" name="checkbox_filter_b" value="1" checked/>';
}
if(isset($_POST['filter_c']) && isset($_POST['checkbox_filter_c'])){
$filter_c = trim($_POST['filter_c']);
$checkbox_filter_c = '<input type="checkbox" name="checkbox_filter_c" value="1" checked/>';
}
}
echo <<<FORM
<form method="POST" action="">
<p>Inputfield a: <input type="text" name="filter_a" value="$filter_a" size="20"> filter for a: on/off:$checkbox_filter_a</p>
<p>Inputfield b: <input type="text" name="filter_b" value="$filter_b" size="20"> filter for b: on/off:$checkbox_filter_b</p>
<p>Inputfield c: <input type="text" name="filter_c" value="$filter_c" size="20"> filter for c: on/off:$checkbox_filter_c</p>
<p><input type="submit" value="Submit"></p>
</form>
FORM;
//now here all you have to do is see if these values are not null and build your query
echo $filter_a.'<br />';
echo $filter_b.'<br />';
echo $filter_c.'<br />';
?>
I have an HTML form - with PHP, I am sending the data of the form into a MySQL database. Some of the answers to the questions on the form have checkboxes. Obviously, the user does not have to tick all checkboxes for one question. I also want to make the other questions (including radio groups) optional.
However, if I submit the form with empty boxes, radio-groups etc, I received a long list of 'Undefined index' error messages for each of them.
How can I get around this? Thanks.
I've used this technique from time to time:
<input type="hidden" name="the_checkbox" value="0" />
<input type="checkbox" name="the_checkbox" value="1" />
note: This gets interpreted differently in different server-side languages, so test and adjust if necessary. Thanks to SimonSimCity for the tip.
Unchecked radio or checkbox elements are not submitted as they are not considered as successful. So you have to check if they are sent using the isset or empty function.
if (isset($_POST['checkbox'])) {
// checkbox has been checked
}
An unchecked checkbox doesn't get sent in the POST data.
You should just check if it's empty:
if (empty($_POST['myCheckbox']))
....
else
....
In PHP empty() and isset() don't generate notices.
Here is a simple workaround using javascript:
before the form containing checkboxes is submitted, set the "off" ones to 0 and check them to make sure they submit. this works for checkbox arrays for example.
///// example //////
given a form with id="formId"
<form id="formId" onSubmit="return formSubmit('formId');" method="POST" action="yourAction.php">
<!-- your checkboxes here . for example: -->
<input type="checkbox" name="cb[]" value="1" >R
<input type="checkbox" name="cb[]" value="1" >G
<input type="checkbox" name="cb[]" value="1" >B
</form>
<?php
if($_POST['cb'][$i] == 0) {
// empty
} elseif ($_POST['cb'][$i] == 1) {
// checked
} else {
// ????
}
?>
<script>
function formSubmit(formId){
var theForm = document.getElementById(formId); // get the form
var cb = theForm.getElementsByTagName('input'); // get the inputs
for(var i=0;i<cb.length;i++){
if(cb[i].type=='checkbox' && !cb[i].checked) // if this is an unchecked checkbox
{
cb[i].value = 0; // set the value to "off"
cb[i].checked = true; // make sure it submits
}
}
return true;
}
</script>
To add to fmsf's code, when adding checkboxes I make them an array by having [] in the name
<FORM METHOD=POST ACTION="statistics.jsp?q=1&g=1">
<input type="radio" name="gerais_radio" value="primeiras">Primeiras Consultas por medico<br/>
<input type="radio" name="gerais_radio" value="salas">Consultas por Sala <br/>
<input type="radio" name="gerais_radio" value="assistencia">Pacientes por assistencia<br/>
<input type="checkbox" name="option[]" value="Option1">Option1<br/>
<input type="checkbox" name="option[]" value="Option2">Option2<br/>
<input type="checkbox" name="option[]" value="Option3">Option3<br/>
<input type="submit" value="Ver">
Use this
$myvalue = (isset($_POST['checkbox']) ? $_POST['checkbox'] : 0;
Or substituting whatever your no value is for the 0
We are trouble on detecting which one checked or not.
If you are populating form in a for loop, please use value property as a data holder:
<?php for($i=1;$i<6;$i++):?>
<input type="checkbox" name="active[]" value="<?php echo $i ?>"
<?endfor;?>
If submit form you'll get order numbers of checkboxes that checked (in this case I checked 3rd and 4th checkboxes):
array(1) {
["active"]=>
array(2) {
[0]=>
string(1) "3"
[1]=>
string(1) "4"
}
}
When you are processing form data in loop, let's say in post.php, use following code to detect if related row is selected:
if(in_array($_POST['active'] ,$i))
$answer_result = true;
else
$answer_result = false;
Final code for testing:
<?php if (isset($_POST) && !empty($_POST)):
echo '<pre>';
var_dump($_POST);
echo '</pre>';
endif;
?>
<form action="test.php" method="post">
<?php for($i=1;$i<6;$i++):?>
<input type="checkbox" name="active[]" value="<?php echo $i; ?>" />
<?php endfor;?>
<button type="submit">Submit</button>
</form>
Although many answers were submitted, I had to improvise for my own solution because I used the customized check-boxes. In other words, none of the answers worked for me.
What I wanted to get is an array of check-boxes, with on and off values. The trick was to submit for each check-box on/off value a separator. Lets say that the separator is ";" so the string you get is
;, on, ;, ;, ;
Then, once you get your post, simply split the data into array using the "," as a character for splitting, and then if the array element contains "on", the check-box is on, otherwise, it is off.
For each check-box, change the ID, everything else is the same... and syntax that repeats is:
<div>
<input type="hidden" name="onoffswitch" class="onoffswitch-checkbox" value=";" />
...some other custom code here...
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch1" checked>
</div>
EDIT: instead of the ";", you can use some KEY string value, and that way you will know that you did not mess up the order, once the POST is obtained on the server-side... that way you can easily create a Map, Hash, or whatever. PS: keep them both within the same div tag.