if ($_POST) {
$family = array("Rob", "Kirsten", "Tommy", "Ralphie");
$isKnown = false;
foreach ($family as $value) {
if ($value == $_POST['name']) {
$isKnown = true;
}
}
if ($isKnown) {
echo "Hi there ".$_POST['name']."!";
} else {
echo "I don't know you.";
}
}
<form method="post">
<p>What is your name?</p>
<p><input type="text" name="name"></p>
<p><input type="submit" value="Submit"></p>
</form>
Now isKnown = false but in the last if statement
if ($isKnown) {
echo "Hi there ".$_POST['name']."!";
} else {
echo "I don't know you.";
}
I can't understand it... Now $isKnown = false and it says when $isknown is false say the code that would saying when isknown is true...
I understand all code but the only thing I can't is in last if what is the value of $isKnown and how it got this value.
What the value of $isknown in this if statement: true or false?
The code works in the following way.If you have submitted the form,then only the value $isknown is set.If it is set, the default value of $isknown is false.
If $_POST['name'] is present in $family, then $isknown is set to true.
Now incase of if($isknown), if $isknown is true,it will echo hi there $_POST['name'] and if $unknown is false, it will echo i dont know u
So, the following is the flow of what you wanted to do:
First, we receive value(s) of $_POST['name'] via a form post and we set the value of variable $isKnown to false.
Then we will the value of $_POST['name'] in the given array $family.
If $_POST['name'] matches one of the values in $family array then we will set the value of $isKnown to true and in the end we will be getting the message on the boolean value of $isKnown.
Actually there is a shorter way to that:
if(!empty($_POST['name'])){
$family = array("Rob", "Kirsten", "Tommy", "Ralphie");
if(in_array($_POST['name'], $family)){
echo "Hi there ".$_POST['name']."!";
}else{
echo "I don't know you.";
}
}
Related
I have a form and php that submits the values, how do I make the php to check if the values are not empty?
Server code
$XX = mysqli_real_escape_string($link, $_REQUEST['XX']);
$YY = mysqli_real_escape_string($link, $_REQUEST['YY']);
if(empty($XX) || empty($YY))
{
echo "You need to fill in XX or YY";
}
Form markup:
<form method="POST" action="">
<label for="XX">XX</label><br>
<label for="YY">YY</label><br>
<input type="text" name="XX" id="XX"><br>
<input type="text" name="YY" id="YY"><br>
<input class="button" type="submit" value="submit"><br>
</form>
Assuming you are trying to check that at least one of these inputs has been set as your echoed message suggests then you need to use an and && and not an or || like this
if(empty($XX) && empty($YY))
{
echo "You need to fill in XX or YY";
}
PHP has three useful functions to test the value of a variable, you need to understand how these functions work in order to use them properly, below is a short description for each, hope it helps
isset()
Determines if a variable is set and is NOT NULL
So if the value assigned is "" or 0 or “0” or false the return will be true, if is NULL it will return false.
$var = '';
if(isset($var)) {
echo 'The variable $var is set.';
}
unset($var);
if(!sset($var)) {
echo 'The variable $var is not set';
}
Empty()
Determines if a variable is empty
So if the value is "" or 0 or 0.0 or "0" or NULL or False or [] it will return true
$var = '';
if(empty($var)) {
echo 'The variable $var is empty or not set';
}
is_null()
It returns true only if a variable is NULL.
$var = NULL;
if(is_null($var)) {
echo 'The variable $var is NULL';
}
if(is_null($foo)) {
echo 'The variable $foo is inexistent so the value is NULL and will evaluate to true';
}
Here is my sample code:
$issue_id = $_POST['issue_id'];
if(!empty($issue_id)){
echo 'true';
}
else{
echo 'false';
}
If I pass 0 to $_POST['issue_id'] by form submitting then it echo false. Which I want is: Condition will be true if the following conditions are fulfilled:
1. true when I pass any value having 0.
2. false when I don't pass any value. i.e: $_POST['issue_id'] is undefined.
I also tried this:
if(!isset($issue_id)){
echo 'true';
}
else{
echo 'false';
}
if(!empty($issue_id) || $issue==0){
echo 'true';
}
else{
echo 'false';
}
The last one is okay, meaning if I pass any value having ZERO then it will echo true. But it will also echo true if I don't pass any value. Any idea?
The last is okay, meaning if I pass any value having ZERO then it echo true. But it also echo true if I don't pass any value. Any idea?
if (isset($_POST["issue_id"]) && $_POST["issue_id"] !== "") {
}
please notice I used !== not !=. this is why:
0 == "" // true
0 === "" // false
See more at http://php.net/manual/en/language.operators.comparison.php
also if you are expecting number you can use
if (isset($_POST["issue_id"]) && is_numeric($_POST["issue_id"])) {
}
since is_numeric("") returns false
http://php.net/manual/en/function.is-numeric.php
Alternatively if you expect number good option is filter_var
if (isset($_POST["issue_id"]) {
$issue_id = filter_var($_POST["issue_id"], FILTER_VALIDATE_INT);
if ($issue_id !== false) {
}
}
since filter_var("", FILTER_VALIDATE_INT) will returns false and filter_var("0", FILTER_VALIDATE_INT) will return (int) 0
http://php.net/manual/en/function.filter-var.php
if(isset($_POST['issue_id'])) {
if($_POST['issue_id'] == 0) {
echo "true";
}
else {
echo "false";
}
}
When you get data from a form, remember:
All text boxes, whether input or textarea will come as strings. That includes empty text boxes, and text boxes which contain numbers.
All selected buttons will have a value, but buttons which are not selected will not be present at all. This includes radio buttons, check boxes and actual buttons.
This means that $_POST['issue_id'] will be the string '0', which is actually truthy.
If you need it to be an integer, use something like: $issue_id=intval($_POST['issue_id']);
#Abdus Sattar Bhuiyan you can also full fill your two condition like below one:
<?php
$_POST["issue_id"] = "0";
$issue_id = isset($_POST['issue_id']) ? (!empty($_POST['issue_id']) || $_POST['issue_id'] === 0 || $_POST['issue_id'] === "0") ? true : false : false;
if($issue_id){
echo 'true';
}
else{
echo 'false';
}
My requirement is to set two values in an html form and pass those values into an PHP file where i will check wither these value is set or not set.If any one or two of the field is blank than it will show invalid input. And if the values are set (including 0) than it will do some action like as adding operation.But the problem is that if i set 0 it takes the value as empty value than shows invalid and also shows 0 after the invalid input. is this because add method is called.any explanation ?
please anyone help me to understand it clearly and also release me from the confusion of 0 and empty check.
My code is here,
HTML:
<input type="number" name="num1"">
<input type="number" name="num2">
<input type="submit" name="add" value="+">
PHP:
<?php
class calculator_oop
{
public $num1;
public $num2;
public $result;
public function __construct($number1,$number2){
if( ((empty($number1) || empty($number2)))) {
echo "Invalid inputs ";
}
else{
$this->num1 = $number1;
$this->num2 = $number2;
}
}
public function add(){
return $this->result = $this->num1 + $this->num2;
}
}
$ob = new calculator_oop($_POST['num1'],$_POST['num2']);
if($_POST['add'] =='+' ){
echo $ob-> add();
}
When I keep the field blank, I just wanna know why 0 appears after invalid input when I let them blank.
output:
Invalid input 0
What's happening here is, 0 is considered as being empty (consult the reference on this below), but you've also (or may have) entered 0 in the input(s), to which in the eye of PHP and at the time of execution, is considered as being "not empty" at the same time, since the input(s) was/were not left "empty" which is sort of fighting for precedence/contradicting itself at the same time.
What you want/need to check is to see if it/they is/are numeric or not by using is_numeric() and using another conditional statement, rather than in one condition in the second statement.
Additionally, you could add an extra condition to check if the inputs are left empty, and adding required to each input, but don't rely on this solely.
if( (!isset($number1,$number2 ))
|| !is_numeric($number1)
|| !is_numeric($number2) ) {
echo "Invalid input ";
}
References:
http://php.net/empty
In php, is 0 treated as empty?
NOTE:
Edit: After revisiting the question and during the time I was writing this, noticed you have posted your form.
Since you did not post your HTML form, this is the following that it was tested with:
<?php
// https://stackoverflow.com/q/41418885/
class calculator_oop
{
public $num1;
public $num2;
public $result;
public function __construct($number1,$number2){
// if( (!isset($number1,$number2 )) || (empty($number1 || $number2))) {
if( (!isset($number1,$number2 )) || !is_numeric($number1) || !is_numeric($number2) ) {
echo "Invalid input ";
}
else{
$this->num1 = $number1;
$this->num2 = $number2;
}
}
public function add(){
return $this->result = $this->num1 + $this->num2;
}
}
if(isset($_POST['submit'])){
$ob = new calculator_oop($_POST['num1'],$_POST['num2']);
if($_POST['add'] =='+' ){
echo $ob-> add();
}
}
?>
<form action="" method="post">
Number 1:
<input type="text" name="num1">
<br>
Number 2:
<input type="text" name="num2">
<br>
<input type="text" name="add" value="+" readonly>
<br>
<input type="submit" name="submit" value="Submit">
</form>
In PHP, the following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
if you want to test zero use :
$var == 0
or
$var == "0"
you have to understand this :
<?php
$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if (isset($var)) {
echo '$var is set even though it is empty';
}
?>
Please read : http://php.net/manual/en/function.empty.php
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I've been figuring out how to do this but it seems not to be working.
My code for the form:
<form name="register" method="POST" action="php\reg.php">
<label>Email:</label>
<input type="email" name="email"/>
.
.
.
</form>
Code for the "reg.php" file:
if (isset($_POST['email'])) {
echo "success!";
} else {
echo "empty!";
}
?>
Problem is, whenever I input or not in the email textbox, isset function always returns the true value. how can I resolve this??
All answers that tell you about using isset() and empty() to check form values are... bad. Use one of the filter functions to check if a POST/GET/COOKIE variable is present and validate or sanitize it. Here is an example:
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
if ($email === NULL) {
die("Email field not present in form");
} elseif ($email === FALSE) {
die("Email is present but its value is invalid");
}
Note: the empty() function has a gotcha and I would not recommend using it for form validation unless you understand exactly what it does: it returns true for all falsy values. This means 0 is considered empty which is often an acceptable value in certain cases. Example (bad one):
if (empty($_POST["number_of_children"])) {
// triggers even when user enters 0
die("number of children field is empty");
}
isset() checks if the values is set, so it's true even if the value is empty string. Use empty():
if (empty($_POST['email']) == false) {
echo "success!";
}else{
echo "empty!";
}
<?php
if (!empty($_POST['email'])) {
echo "success!";
}else{
echo "empty!";
}
?>
try this-
<?php
if (!empty($_POST['email'])) {
echo "success!";
}else{
echo "empty!";
}
?>
Null and/or empty strings are still set if the variable is declared.
$_POST contains empty string for your value, and isset() returns true. Use empty() or add != '' in your if condition.try this:
if (!empty($_POST['email']))
Try to use empty() function to check if there is anything in email filed of $_POST array.
The example code based on your code is below:
<?php
if (isset($_POST['email']) && !empty($_POST['email'])) {
echo "success!";
} else {
echo "empty!";
}
?>
<?php
if (isset($_POST['email']) && $_POST['email'] != "") {
echo "success!";
}else{
echo "empty!";
}
?>
try this way
I have some code written in php to validate a postcode field in my form. The code is meant to check that the field is not empty (mandatory) and matches one of 5 usable postcodes, if not it displays an alert. The problem i am having is that when i leave the field empty and hit the submit button the proper alert is show but if i enter a wrong value and hit submit the form just loads to a blank screen, can anyone spot a mistake in my code? :
<?php
if (isset($_POST['submit'])) {
$post = $_POST["post"];
$words = array('2747','2750','2753','2760','2777');
$msgp = "";
if (!empty($post)) {
foreach ($words as $item)
{
if (strpos($post, $item) !== false)
return true;
}
$msgp = '<span class="error"><b>Please enter correct postcode</b></span>';
return false;
} else if(empty($post)) {
$msgp = '<span class="error"><b>Please enter postcode</b></span>';
}
}
?>
<form name="eoiform" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi">
<b>Post Code</b>
<br>
<input type="text" id="post" name="post" /><?php echo $msgp; ?>
</form>
return? Return where?
When you return in your main code, it's (nearly) the same as die()'ing.
So when you return, the remaining PHP won't be executed anymore.
I'd consider to set some variable like $success = true/false; instead of returning.
You return false after $msgp = '<span class="error"><b>Please enter correct postcode</b></span>'; therefor you do not continue to the form below... remove the returns from your code to be able to handle and show an error.
You are using return. Are you in a function() {} ? If so, all your variables are in function scope. You could do global $msgp; to make the variable accessible outside of the function.
If not... then you shouldn't use return.
Change php code to
<?php
if (isset($_POST['post'])) {
$post = intval($_POST["post"],0);
$words = array(2747,2750,2756,2760,2777);
$msgp = '<span class="error"><b>'.in_array($post,$words) ? "Please enter postcode" : "Please enter correct postcode" .'</b></span>';
}
There are a lot of things that can be simplified. For example codes as int array and using in_array() function. Return statement should be used to return something from method/function using it in global scope then execution of the current script file is ended. There is no need for it here. If there are more $words values you should consider using simple REGEX /[0-9]{4}/ and preg_match()
You want to display $msgp right? Use echo $msgp;. But you can return to nowhere in your code. (put it in a function).
Try this
<?php
$post = $_POST["post"];
$words = array('2747','2750','2753','2760','2777');
$msgp = "<span class='error'><b>Please enter correct postcode</b></span>";
function check($post){
global $words;
$return=true;
if (!empty($post)) {
foreach ($words as $item)
{
if (strpos($post, $item) !== false)
//$return=true;
}
} else if(empty($post)) {
$return=false;
}
return $result;
}
$return=check($post);
if($return === true){
// echo you are right!
}
else {
echo $msgp;
}