chaining if else statements - php

I have a form field in my website which i use for a table in my database. i'm using checkboxes for a true/false value. In my case my checkboxes send out an empty string if left unchecked.
I made an if else statement to make sure the empty string is made boolean. however, my if else statements only works for the first one ($ringe). the last two ($halskaeder and $armbaand) does not seem to work, as my database does not register any inputs.
I'm guessing my if else statements has flaws or syntax errors, i'm just too hopeless at PHP to figure out what's wrong.
if ($_REQUEST['ringe'] == ""){
$ringe = '0';
}
else {
$ringe = '1';
}
if ($_REQUEST['halskaeder'] == ""){
$halskaeder = '0';
}
else {
$halskaeder = '1';
}
if ($_REQUEST['armbaand'] == ""){
$armbaand = '0';
}
else {
$armbaand = '1';
}
Any help is highly appreciated!
UPDATE!!!
So I realized my issue is that an unchecked checkbox in html doesn't send and signal. So i have to change that no matter what

AFAIK the check box is not sent if it's not checked. You can do something like:
$default = array(
'ringe' => 0,
'halskaeder' => 0,
'armbaand' => 0,
);
$myFormParams = array_replace($default, $_REQUEST);
var_dump($myFormParams);

few Suggestions... I may add more if you post your form..
1) Trim whitespace from user input (unless you need it)
$input = trim($_REQUEST['user_input']);
2) In this case, you should use empty(), because this function checks to see if the variable exists, and if it's empty, and if it's falsy. You can kill three birds with one stone.
3) Use ternary. It's shorthand for what you're doing.
$input = trim($_REQUEST['user_input']);
$input = empty($input) ? "0" : "1";

I found an answer. My problem wasnt the php code, but the checkboxed not sending any input when unchecked. The workaround is simply putting a hidden input field to send a false signal no matter what. You give it the same name attribute as your real checkbox, which will override when checked.
looks like this:
<input type="hidden" name="ringe" value="0" /><input type="checkbox" name="ringe" value="1" /><p>Ringe</p>
thanks for the help though!

Related

Check if array of checkboxes are checked from a form (PHP)

I realize this is a question that has been asked before ("Cannot use [] for reading"), but I'm having trouble wrapping my head around the answer and how to fix my particular function.
function check_required_checkbox($checkbox_name, $error, $is_multiple_checkboxes)
{
global $error_msgs;
if ($is_multiple_checkboxes == true)
{
if (!isset($_POST[$checkbox_name][]))
{
$error_msgs[] = $error;
}
else if ($is_multiple_checkboxes == false)
{
if (!isset($_POST[$checkbox_name]))
{
$error_msgs[] = $error;
}
}
}
The problem line is 6, !isset($_POST[$checkbox_name][]), and I'm not understanding how the correct way I should write it. I saw instances of using brackets but !isset($_POST[{$checkbox_name}][]) isn't correct either.
When I have multiple checkboxes that use name="radda[]", I want my function to check that all of the checkboxes with a specific name are checked, and if not, add $error to the $error_msgs[] array.
EDIT:
I discussed with the department that was requesting a rewrite of the old form. Instead of using checkboxes, I switched it to a list of all of the borrower's rights and responsibilities, and then used a radio button below the list to ask the user to select "yes" or "no" on whether they read the list. Then I made it required to select "yes" or "no" and added validation that if "no" was selected, they wouldn't be able to submit the application. This was far easier than trying to make a bunch of checkboxes required. I do appreciate the help that everyone offered though.
If I understood what you need.
Try to define the $checkbox_name variable and then access the POST.
$checkbox_name = 'radda';
if (isset($_POST[$checkbox_name]) && !is_array($_POST[$checkbox_name]))
{
$error_msgs[] = $error;
}
Something like that should work.
Here is a similar thread: Retrieve an associative array value with a variable as key

php function that checks if checkbox is selected. Field validation issue

Please read my issue carefully, it's a bit tricky.
The function below is used to display whether a checkbox has been checked in a form on both of my 'add' and 'edit' record pages. No problem here.
The problem:
Let's say I have 2 fields 'name' and 'enabled'. Only fields that is validated is 'name'.
When a user edits an existing record and enters an invalid 'name', the form gets validated. If the user un-checked the 'enabled' checkbox (prior value was $field_record_value="1", setting from the database), the checkbox value still set as "1" as it's still coming from the database.
Question:
How do I get the value to set as "0" when the database record ($field_record_value) is set to 1 ?
I know the issue lies in this code:
$is_checked = isset($field_record_value) ? $field_record_value : '0';
I can't seem to figure it out, maybe because I've spent about 2 hours on this and my brain is fried..but I digress :)
//------------------------------------------------
// Function to check if checkbox is selected
//------------------------------------------------
function form_checkbox_selected($field_name, $page = 'add', $field_record_value = '0')
{
if(!empty($_POST[$field_name]) && intval($_POST[$field_name]))
{
$is_checked = '1';
}
else
{
if($page ==' edit')
{
$is_checked = isset($field_record_value) ? $field_record_value : '0';
}
else
{
$is_checked = '0';
}
}
return $is_checked;
}
The problem is that you are expecting an unchecked value for a checkbox, the browser will never send a value for an unchecked checkbox, so the only way you can know a checkbox is in it's unchecked state is by assumption, which you can only assume after the form has been submitted. I would rewrite your function like so:
function form_checkbox_selected /// line wrapped for SO read-ability
($field_name, $page = 'add', $form_submitted = false, $field_record_value = '0'){
if ( form_submitted ) {
$is_checked = !empty($_POST[$field_name]) ? 1 : 0;
}
else if ( $page == 'edit' ) {
/// isset is not required because it will always
/// be defined by $field_record_value = '0' in default params.
$is_checked = $field_record_value ? 1 : 0;
}
else {
$is_checked = 0;
}
return $is_checked;
}
In order to tell if the form has been submitted or not, it is usually best to have a hidden field that you know will always be sent, or you can define a name for your submit button.
<form>
<input name="sent" type="hidden" value="1" />
</form>
<form>
<input name="sent" type="submit" value="Submit Form" />
</form>
Then on the php side you can call your function:
form_checkbox_selected(
'my_field', 'edit', !empty($_POST['sent']), $db['my_field']
);
This now means your php can make a better assumption of what the field's state is when no data has actually been passed in.

Cant get radio button value to post in php

I started with the code from simplemodal, and modified to suit my needs. That went amazingly well. The last issue I have is getting some radio buttons to post. I'll skip the code blocks I don't think are necessary and just show what I think is relevant. I've tried literally dozens of attempts of solutions from php.net, but nothing seems to work.
HTML
<label for='PayPlatform'>Are you willing to pay for a trading platform?</label>
<input type='radio' name='PayPlatform' value='Yes' tabindex='1001' />Yes
<input type='radio' name='PayPlatform' value='No' tabindex='1002' />No
Here's where I can't get the value and my attempt there are two attempts in the codeblock below, they were of course not attempted at the same time.
else if ($action == "send") {
// other elements form values are retrieved fine, just not the below
$PayPlatform = isset($_POST['PayPlatform']) ? ' checked="checked"' : "";
//the ternary above just submits 'checked="checked" no matter which radio is checked
//another attempt
$PayPlatform = isset($_POST["PayPlatform"]);
//this just submits "1" weather yes or no is checked
$token = isset($_POST["token"]) ? $_POST["token"] : "";
// make sure the token matches
if ($token === smcf_token($to)) {
smcf_send($name, $email, $subject, $phone, $message, $PayPlatform);
echo "Your message was successfully sent, you can close this window";
}
else {
echo "Unfortunately, your message could not be verified.";
}
}
$p = (isset($_POST['PayPlatform']) && $_POST['PayPlatform'] == 'Yes');
Boolean true if the yes radio is checked, and false otherwise.
Assume you have the following:
$a = 'Yes';
isset($a); //true
$b = 'No';
isset($b); //true
Strings are considered set, and as PsyCoder said, you'll receive the value values, not Booleans.
Also, on a different (chastise-y) note, this question could have been entirely avoided with a bit of better debugging. The first thing I would have done would have been to var_dump($_POST) and see what the value was. You'd have then seen that $_POST['PayPlatform'] was always Yes or No, and you'd have potentially realized that isset is always true on strings.
You wont get value as checked or unchecked... rather you'll receive the value='No' or value='No' parameter value specified in your html...
if($_POST["PayPlatform"] == "Yes") {
$PayPlatform = true;
}
Keeping it simple :)

PHP + MsSQL = Checkbox problems. Need HELP!

I have been working on this one topic for weeks. I'm creating a webpage that pulls information from MsSQL server. My problem is where there is a section with few check boxes.
The checkboxes are suppose to be checked if they are found in the SQL database.
If the borrower used money from "Savings", "Checking" and "Stock" those checkboxes should be checked in HTML page. In my case it is only checking whatever is on the first row of the SQL search list. So if the list has "Saving" on the first row, only the "Saving" checkbox will be checked not the rest on the list. I tried using loop (while($r->EOF)), but then it picks whatever is on the end of the list. Here is what I am using to pull data from the SQL server. Thank you in advance for your help. Really appreciate it!
function __construct($_ldid, $_lrid)
$this->ldid = $_ldid;
$this->lrid = $_lrid;
//$loan is defined in the PHP.class (which is shown below).
$q = ("SELECT * FROM Tabel_name where loan_id = 885775")
$v = array($_ldid, $_lrid);
$r = $db->Execute($q, $v);
$this->downpaymenttype = $r->fields; //<- I think I have this line done wrong because it is suppose to store the outputs to an array.
//So wherever the "$loan" is in HTML page, it will take the outputs from the above statement.
//The above code, which is in PHP.class file, outputs the following(or suppose to):
1 885775 Checking
2 885775 Saving
3 885775 Gift
In the HTML webpage, the following codes should check mark the boxes according to the outputs:
<input type="checkbox" name="DPS1[]" id="DPS1-{$key}" {if $loan-> downpaymenttype.downpaymentsource == "Checking"} checked {/if}/>
<input type="checkbox" name="DPS2[]" id="DPS2-{$key}" {if $loan-> downpaymenttype.downpaymentsource == "Saving"} checked {/if}/>
<input type="checkbox" name="DPS3[]" id="DPS3-{$key}" {if $loan-> downpaymenttype.downpaymentsource == "Gift"} checked {/if}/>
Only the "checking" checkbox is getting checked because that's the one on the first row.
I also tried to loop, but it is not storing in array (I guess I don't know how to use the array for session)
$q = ("SELECT Tabel_name FROM loan_downpaymentsource where loan_id = 885775");
$v = array($_ldid, $_lrid));
$r = $db->Execute($q, $v);
while(!$r->EOF) {
$this->downpaymenttype = $r->fields;
$r->MoveNext();
}
Add a loop to go through your results before displaying and set flags. $r->fields is only going to grab the fields for the current row. You need to go through your entire rowset to see if the others are set.
Something like (It looks like you're using adodb or something like that)
$checking = false;
$saving = false;
$gift = false;
while(!$r->EOF){
$row = $r->fields;
switch($row->downpaymenttype){
case 'Checking':
$checking=true;
break;
case 'Saving':
$saving=true;
break;
case 'Gift':
$gift=true;
break;
default:
break;
}
$r->moveNext();
}
Now on your view check the flags. I've not used smarty but you'll have to pass those flags to your template as well as I'm sure you know, and then change your checkbox lines to check if each flag is true/false.
Hope that helps!

checkbox status "checked" by default problem

I have a page with search form on it and table with search results below. In search form i have checkbox "Search in this category". What i'm doing to check it by default :
if(!isset($_SESSION['inthiscat'])){
$_SESSION['inthiscat'] = 'on' ;
$checked = 'checked';
}
$_GET['inthiscat'] = $_SESSION['inthiscat'];
checkbox code : INPUT type="checkbox" name="inthiscat"<?=$checked?>.
Link to next page of results index.php?inthiscat=$_GET['inthiscat'].
So the problem is when i uncheck "Search in this category" its still checked when i going to next page of results. How to fix it and what i'm doing wrong? Session startet of course.
Firstly, do you really need SESSION variables for this? If you want box to be checked when GET parameter is not specified, you do not need SESSIONs at all.
Assuming you want to preserve the behaviour in case someone removes the GET parameter:
<?php
session_start();
//......
//......
$checked='checked';
if(isset($_REQUEST['inthiscat'])) {
// Form input and url GET parameters take precedence
if($_REQUEST['inthiscat'] != 'checked') { $checked = ''; };
} else if(isset($_SESSION['inthiscat'])) {
// Next, use session variable if it exists
if($_SESSION['inthiscat'] != 'checked') { $checked = ''; };
};
$_SESSION['inthiscat']=$checked;
?>
Note:
1) Assigning values to GET array is not a good practice.
2) I assume you are using correct syntax for your FORM submit.
3) IMO, you could remove the SESSION variable as you are explicitly passing as GET parameter in the subsequent urls. Or dont use the GET parameter in urls.
Problem is: when you uncheck the checkbox and go to the next page, $_SESSION['inthiscat'] will still be unset - where did you change it?
Here is the code:
if (isset($_GET['inthiscat'])) {
$_SESSION['inthiscat'] = $_GET['inthiscat'];
}
if (!isset($_SESSION['inthiscat'])) {
$checked = 'checked';
} else {
if ($_SESSION['inthiscat'] == 'on') {
$checked = 'checked';
} else {
$cheked = '';
}
}
Assuming this HTML: <INPUT type="checkbox" name="inthiscat" checked="<?=$checked?>" value="on" />
So what it does is:
Looks for the GET data and, if there is, assigns it (can be 'on' or '') to the SESSION;
If there is no SESSION (that means, no GET as well) it's the first page of that kind the user visits, so checked;
If there is a SESSION for inthiscat, it means it's not the first page and GET data has been assigned to the SESSION. So, if it's on, it displays the mark; else, it does not.

Categories