php if elseif then what? - php

This is my PHP code
The problem points I have mentioned in comments inside the code portion
if(isset($_POST['submit']))
{
if(isset($_POST['rdoption1']))
{
$var1 = $_POST["rdoption1"];
}
if(isset($_POST['rdoption2']))
{
$var2 = $_POST["rdoption2"];
}
if(!isset($_POST['rdoption1']))
{
$message = "Please select Option1";
}
elseif(!isset($_POST['rdoption2']))
{
$message = "Please select Option2";
}
elseif($_POST['rdoption2'] == "checkSetXY")
{
if($_POST["valXLocation"] == "")
{
$message = "You forget to enter X value.";
}
elseif($_POST["valYLocation"] == "")
{
$message = "You forget to enter Y value.";
}
} // till here all is good. I get all error messages if anything is left vacant or not clicked on radio button
elseif(empty($_POST['txtoption3'])) //this is not working //the issue is if i select rdoption1 any option and rdoption2 checkDefault next code logic work.. but next code logic does not work when i click on the radio of checkSetXY and enter x and y values.. It simply does not execute code further..
{
$message = "Please enter your name.";
}
else
{
//insert into db
}
}
This is html form with PHP echos
Here I'm getting messages where they shall be but not when I select checkSetXY value
<?php if(!empty($message)){ echo $message; } ?>
<form id="form1" name="form1" method="post" action="form1.php">
Space portion:
<input type="radio" name="rdoption1" value="RJ"/>space 1
<input type="radio" name="rdoption1" value="SM" />space 2
Pixel Location
<div class="formText">
<input type="radio" name="rdoption2" value="checkSetXY"/> Specify Location
X: <input type="text" id="locField" name="valXLocation">
Y: <input type="text" id="locField" name="valYLocation">
<input type="radio" name="rdoption2" value="checkDefault"/>Default
<input type="text" class="input" name="txtoption3">
<input type="submit" name="submit" value="Submit">
</form>
Now I'm confused why is it not taking elseif of txtoption3
Any help? Thanks in advance

That won't work because, it will be always set. So, use empty();
elseif(empty($_POST['txtoption3'])) //this is not working
Explanation
You are posting a form input. When you send it without filling anything, it just sends this value. ""
An empty string is not equal to null or not set.
Also, as Peter Szymkowski said, check out the fiddle.

Textfields are set if they are empty. You have to check with empty($_POST['txtoption3']) .

that is the else for
if($_POST['rdoption2'] == "checkSetXY")
which I guess is true so it will not go into that else

Related

Testing PHP POST empty values - unexpected result - What am I missing?

I am following a tutorial but I keep getting a TRUE result that shouldn't be correct if I click the submit button WITHOUT filling in any value in the name field.
The first test works as expected, but the second and third test keep returning TRUE when they should return FALSE (leaving the input empty).
What am I missing, not understanding, or doing wrong? This should be simple.
Any help or suggestions are appreciated.
Here is the very simple script:
<?php
//This one works correctly
if(!empty($_POST['name'])) {
echo "There is input here <br>";
} else {
echo "You have not input any info yet. <br>";
}
//This returns true even if I leave the field empty
if(isset($_POST['name'])) {
echo "A name has been input <br>";
} else {
echo "You have not input your name yet. <br>";
}
//This returns true also when it shouldn't
if(filter_has_var(INPUT_POST, 'name')) {
echo $_POST['name'] . ' <- Name Input!<br>';
} else {
echo 'No Name Input.';
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p><label for="name">Name:</label> <input type="text" name="name"
id="name" size="30" value=""></p>
<p><input type="submit" value="SEND"></p>
</form>
empty does what is says, checks if empty (is empty if not existing aswell)
isset checks if the var exists, no if anything has been set
filter_has_var pretty much the same as isset
place a print_r($_POST) at the top of your file, you will understand :)
You need to check the value to see if it's empty:
if(isset($_POST['name']) && !empty($_POST['name'])) {
http://php.net/manual/en/function.empty.php

Why Won't my PHP Form Code work Correctly?

I am trying to create a form in php with an else/if statement that asks the user for their name and age. It greets them with a welcome message and their name, and then if their age is 16 or over, the statement echos "You are old enough to volunteer for our program." If the user is under the age of 16, the statement will echo "Sorry, try again when you are older. Here is my code:
<form action="" method="post">
Name: <input type="text" name="postName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
echo $_POST['postName'];
?>
!
<br>
<?php
$age = 'age';
if ($age>=16)
{
echo $_POST["you are old enough to volunteer for our program!"];
}
else {
echo $_POST["Sorry, try again when you're 16 or older."];
}
?>
The input form is shown correctly, but "Sorry, try again when you're 16 or older" already appears when I open the web page and when I put my name and age in there, the welcome message with the users name works correctly, but absolutely nothing happens with the age statement. It still just says "try again when you're older" no matter what age I put in. HELP :(
For starters you need to use $_POST["age"] and not age. Also you should check if you are using get or post using $_SERVER['REQUEST_METHOD'].
If ($_SERVER['REQUEST_METHOD'] == "POST") {
// HandleForm
} else {
// showForm
}

Validating radio buttons in php

I'm new to PHP and trying to write code to test whether or not a user has clicked a radio button in response to a survey question. There are numerous radio buttons. If they haven't clicked on one then I'd like to issue an error to the user. I've tried a couple of approaches, but haven't found anything that works. Here is my current code and the error message I get. For the PHP script, I've tried all of the three following examples:
....
if ($_POST['degree_type'] == "MS"||"MA"||"MBA"||"JD"||"PhD") {
$degree_type = ($_POST['degree_type']);
} else if ($_POST['degree_type'] == null) {
$errors[] = 'Please select a degree type.';
}
if (isset($_POST['degree_type'])) {
$errors[] = 'Please select a degree type.';
} else {
$degree_type= $_POST['degree_type'];
}
if (array_key_exists('degree_type', $_POST)) {
$degree_type = ($_POST['degree_type']);
} else {
$errors[] = 'Please select a degree type.';
}
....
Here is my html, located in the same page and below the PHP.
<table>
<tr>
<td class="span6">What type of degree?</td>
<td class="span6">
<input type="radio" name="degree_type" value="MA"
<?php if (($_POST['degree_type']) == 'MA') {echo 'checked="checked"';} ?>
>MA
<input type="radio" name="degree_type" value="MS"
<?php if (($_POST['degree_type']) == 'MS') {echo 'checked="checked"';} ?>
>MS
<input type="radio" name="degree_type" value="MBA"
<?php if (($_POST['degree_type']) == 'MBA') {echo 'checked="checked"';} ?>
>MBA
<input type="radio" name="degree_type" value="JD"
<?php if (($_POST['degree_type']) == 'JD') {echo 'checked="checked"';} ?>
>JD
</td>
</tr>
ETC....
I get an "undefined index" error on each of the HTML lines referencing a radio button. I understand this might be easier to do in JavaScript, but I don't know much about JS... A detailed response would be much appreciated!
Thanks!
If you're getting an undefined error on the HTML page, just can add an isset() check to the logic where you're printing out the value. E.g.:
<input type="radio" name="degree_type" value="JD" <?php if (($_POST['degree_type']) == 'JD') {echo 'checked="checked"';} ?> >JD
Becomes
<input type="radio" name="degree_type" value="JD" <?php if (isset($_POST['degree_type']) && $_POST['degree_type'] == 'JD') {echo 'checked="checked"';} ?>>JD
An 'undefined index' error in PHP means that you are using an undefined variable in an expression. So for example, when you did:
<?php if (($_POST['degree_type']) == 'MA') {echo 'checked="checked"';} ?>
$_POST['degree_type'] was undefined. There's a couple of different possible reasons why the variables are undefined. I'd have to see the rest of the PHP file to know the exact cause.
One reason could be that the form was not properly submitted. Another reason could be that the expression was evaluated before the form was submitted.
Either way, the code below should work. Note that I'm checking if each field is set before attempting to validate it or compare it's value.
NOTE:
Obviously you have to have a proper HTML doctype, opening and closing body tags etc. The HTML in this example is only the form portion of the page.
<!-- myform.php -->
<form name="my-form" method="POST" action="/myform.php">
<span>What degree do you have?</span>
<label for="bs">BS</label>
<input type="radio" name="degree" id="bs" value="BS" <?php if(isset($degree) && $degree == 'BS') echo 'checked="checked"';?> />
<label for="ma">MA</label>
<input type="radio" name="degree" id="ma" value="MA" <?php if(isset($degree) && $degree == 'MA') echo 'checked="checked"';?> />
<label for="phd">PHD</label>
<input type="radio" name="degree" id="phd" value="PHD" <?php if(isset($degree) && $degree == 'PHD') echo 'checked="checked"';?> />
<span>Which do you like better?</span>
<label for="steak">steak</label>
<input type="radio" name="food" id="steak" value="steak" <?php if(isset($food) && $food == 'steak') echo 'checked="checked"';?> />
<label for="lobster">lobster</label>
<input type="radio" name="food" id="lobster" value="lobster" <?php if(isset($food) && $food == 'lobster') echo 'checked="checked"';?> />
<input type="hidden" name="submitted" value="submitted" />
<input type="submit" name="submit" value="submit" />
</form>
<?php
if (isset($_POST['submitted'])) {
$errors = array();
if (isset($_POST['degree'])) {
$degree = $_POST['degree'];
} else {
$errors[] = 'Please select your degree type.';
}
if (isset($_POST['food'])) {
$food = $_POST['food'];
} else {
$errors[] = 'Please select your food preference.';
}
if (count($errors) > 0) {
foreach($errors as $error) {
echo $error;
}
} else {
echo 'Thank you for your submission.';
}
}
?>
The reason you see these notices is because $_POST['degree_type'] is simply not set. Either by typo, or it just didn't get submitted (because you didn't select any before submitting the form).
Also note,
if ($_POST['degree_type'] == "MS"||"MA"||"MBA"||"JD"||"PhD") {
It doesn't work that way. This will check that $_POST['degree_type'] == "MS" OR: "MS" is truthy (always true) OR "MA" is truthy (always true)... see where I'm heading?
if (in_array($_POST['degree_type'], array("MS", "MA", "MBA", "JS", "PhD")) {
Is a better alternative.
Unrelated:
You should really use <label> elements to markup your labels. Example:
<label><input type="radio" name="degree_type" value="MA"> MA</label>.
This will have MA clickable.
When a form is submitted with no member of a radio button group (defined as the group of radio buttons whose name attributes are the same) selected, the submitted data doesn't include that name at all.
This is why you're getting the "undefined index" error (actually a notice); when you test the value of $_POST['degree_type'], and no radio button named "degree_type" was selected, $_POST['degree_type'] doesn't exist at all.
Fortunately, this simplifies your validation task. By calling array_key_exists('degree_type', $_POST), you can find out whether or not the key is present, and thus whether or not a radio button was selected, without prompting the PHP "undefined index" notice. If the function call returns true, you know that a radio button was selected; otherwise, you know one wasn't, and that's what your validation is trying to determine. Therefore:
if (array_key_exists('degree_type', $_POST)) {
$degree_type = $_POST['degree_type'];
}
else {
array_push($errors, "Please select a degree type.");
};
will cleanly accomplish your task.
//set a default
$degree_type = "";
if (isset($_POST['degree_type'])) {
$degree_type = $_POST['degree_type'];
} else {
$errors[] = 'Please select a degree type.';
}
Then instead of using
if (($_POST['degree_type']) == 'MA')
for your checks, use:
if($degree_type == 'MA')
undefined index means that the key you are using hasn't been initialized. So $_POST['degree_type'] won't appear until after the first time the form is submitted.

Validate empty field with php

I need to validate an empty field with php and javascript, but both of the methods fail.
<form method="POST" name="contact_form"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<input type="text" name="pickupaddress" value="<?
if($pickupaddress == ''){
echo "";}
else{echo htmlentities($pickupaddress);}?> " id="pickupaddress"/>
<input type ="submit" name="submit" value"Reserve"/>
</form>
//////// Php validation DOES NOT WORK////////
$pickupaddress ='';
$err ='';
$pickupaddress = $_POST['pickupaddress'];
if($pickupaddress == ''){ //if empty field, I also tried == ""
$err.="Please provide pick up address.";
}
///// Javascript validation does not work.
if(form.pickupaddress ==""){
alert("empty address!");
}
//when I click submit nothing happens.
//I am thinking the problem is with
htmlentities($pickupaddress);
//Thanks for your help.
Here is hopefully simpler answer:
$pickupaddress = trim($_POST['pickupaddress']); //trims the string
if (empty($pickupaddress)){ //if empty field
$err.="Please provide pick up address.";
}
On the php side you can try trimming the value and then using empty() on the next line, though that will also invalidate 0, false, null, and other such values. Or you can try using isset.
For the javascript side you can try this function:
function IsEmpty(aTextField) {
if ((aTextField.value.length==0) ||
(aTextField.value==null)) {
return true;
}
else { return false; }
}
found here: http://www.codetoad.com/javascript/isempty.asp
$cid = $_POST['category'];
if (!empty($_POST['category']))
{
echo "<script>alert('empty field');</script>";
}
Where are you defining pickupaddress? Is it before the form or after? If the variable isn't defined, and depending on your server configuration, the value field of the input could be
Notice: undefined variable pickupaddress
Thus making the value != ''.
View your page source to ensure that the value is indeed empty.
there was a spave " " in your string: echo htmlentities($pickupaddress);}?> "
maybe that was the reason, because it was not an empty string but it was a space?
<form method="POST" name="contact_form"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<input type="text" name="pickupaddress" value="<?
if($pickupaddress != '') {
echo htmlentities($pickupaddress);
}?>" id="pickupaddress"/>
<input type ="submit" name="submit" value"Reserve"/>
</form>
and i guess you might want to have checked if the post value is set:
if(isset($_POST['pickupaddress'])) {
$pickupaddress = $_POST['pickupaddress'];
}
the php way works for me like that ;) (the message is displayed if i dont write anything)

PHP How to check if text field matches var

Well then, this is likely to be the n-th time someone is asking this, but honestly I didn't grab anything useful spending the last hour or so on Google. What I want to do is rather trivia, or so I thought. I have this working in Java Script but want to move it to PHP. In brief:
declare a var with a static value
add text field into which user is asked to enter value of above var
check if field is a) empty, b) non-empty mismatch, or c) non-empty match
My (limited) PHP wisdom has lead me into believing it ought to be something like the below, but apparently it's not. I'd very much appreciate any insight, tha.
<?php
$coconew = "blah";
if (isset ($_POST["cocosub"])) {
if ($_POST["cocoval"] == "") {
echo "empty";
} else {
if ($_POST["cocoval"] != $coconew) {
echo "mismatch";
} else {
echo "match";
}
}
}
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" id="cocosub" method="post">
<div>
<?php echo $coconew; ?>
<input type="text" id="cocoval">
<input type="submit">
</div>
</form>
You need to change
<input type="text" id="cocoval">
to
<input type="text" name="cocoval">
There are other (and probably better) ways to do this, but you are on the right track.
$_POST only looks for the name attribute of form elements, so modify your form as such:
<?php
$coconew = "blah";
if (isset ($_POST["cocoval"])) {
if ($_POST["cocoval"] === "") {
echo "empty";
} else {
if ($_POST["cocoval"] !== $coconew) {
echo "mismatch";
} else {
echo "match";
}
}
}
?>
<form id="cocosub" method="post">
<div>
<?php echo $coconew; ?>
<input type="text" id="cocoval" name="cocoval">
<input type="submit">
</div>
</form>
(I made a few other changes, you want to check isset on the element, not the form, it will POST to the same page if you don't give it an attribute [so no need to add the echo], and adding better type checking in your php)
in addition to the other answers already posted, you might also be interested in PHP's session support (depending on how "static" you need your static variables to be). That's where you'd put $cocoval and any other variables if you need to save their values across multiple requests for the same URL by the same user. See here for more info:
http://php.net/manual/en/features.sessions.php and
http://www.php.net/manual/en/book.session.php
This works:
<?php
session_start();
if(isset($_POST["cocosub"])){
$input = trim($_POST["cocoval"]);
if($input == ""){
echo "empty";
} elseif($input != $_SESSION["coconew"]){
echo "mismatch";
} else {
echo "match";
}
}
$_SESSION["coconew"] = substr(md5(uniqid()), 0, 5);
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" id="cocosub" method="post">
<div>
<?php echo $_SESSION["coconew"]; ?>
<input type="text" id="cocoval" name="cocoval">
<input type="submit" name="cocosub">
</div>
</form>
You needed to add name="cocosub" to the Submit button element in order for the first if(isset(...)) condition to be true. That's why the script didn't work. Also, instead of id, you need to use the name="cocoval" in the input text field as well in order for it to carry over into $_POST.

Categories