php check if values in form have been filled - php

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';
}

Related

How $_POST in php operates

my index file is
<body>
<form method="POST" action="post.php" >
<input name="name">
<input type="submit" value="submit">
</form>
</body>
and post.php is
<?php
$sec = 'qaswed';
if($sec == $_POST['name'])
{
echo "true";
}
else
{
echo "false";
}
?>
When I am simply writing the TRUE in place of $_POST['name'] in post.php file then irrespective of what i submit in index file,the result is true as obvious i.e
if($sec == TRUE) { echo "true"; } else { echo "false"; }//true
But, When in index file if i send TRUE in the name parameter then why the output is coming false .. i.e
if($sec == $_POST['name']) { echo "true"; } else { echo "false"; }// false when name=TRUE
when I send this from other page variable (request) then it evaluates to false.why it happens?
When you write if ($sec == TRUE), then it's true, because you are using automatic type conversion with the == operator, and php converts the $sec string to bool type, where since it's not (bool)false(not string 'false'!!!!) or (int)0, it becomes true, and the true === true = true.
If you don't want the php to automatically convert the values in the if, then use === instead of ==, which will also check the type.
In the other case you are sending a "true" string and you have "qaswed" string which is obviously not the same, and since both of them are strings there are no type conversion like in the previous case.
In first comparison value of string 'qaswed' automatically is casted to the boolean value in order to comapre to the bool. When you compare different data types one of it is casted to another type.
If you want to compare also types of the variables you should use Identical Comparison Operator.
var_dump('qaswed'); // string(6) "qaswed"
var_dump((bool)'qaswed'); // bool(true)
var_dump('qaswed' == true); // bool(true)
var_dump('qaswed' === true); // bool(false)
In second case you compare string types.
var_dump('TRUE'); // string(4) "TRUE"
var_dump('qaswed'); // string(6) "qaswed"
var_dump('qaswed' == 'TRUE'); // bool(false)
var_dump('qaswed' === 'TRUE'); // bool(false)
i just added "if (isset($_POST['name']))" for checking the name is set or not
//post.php
<?php
if (isset($_POST['name']))
{
$sec = 'qaswed';
if ($sec == $_POST['name'])
{
echo "true";
}
else
{
echo "false";
}
}
?>

How to treat zero values as true using php?

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';
}

why i get an default output 0 after the invalid inputs?

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

PHP: The value of boolean in if statement

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.";
}
}

Why is $name field never !, even when empty?

I have a basic sign up form, and when checking if a field is not set (if(!$name)) it always goes to 'else', even when the field is empty.
Does anyone know why?
(When i'm trying to check it in reverse (if($name)), it does show the error line. )
*var_dump($name) - always returns a string, never false. I'm guessing thats part of the problem?...
Thanks a lot!!
<?php
$error = '';
if(isset($_POST['submit'])){
$name = trim(filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING));
if( !$name && preg_match("/^([\w]){2,50}$/", $name)){
$error = ' * Please enter a valid name';
}
?>
<form action="" method="post">
<label for="name">Name:</label><br>
<input type="text" name="name"> <br><br>
<input type="submit" name="submit" value="Sign up">
<span class="error"><?= $error ?></span>
</form>
Well, you got wrong IF statement. You are checking if $name is false (it will be only if you send empty string) AND if it's length is between 2-50.
Consider two states:
<?php
$name = 'Login';
$a = !$name; // FALSE! You're variable is OK, but you neg it
$b = preg_match("/^([\w]){2,50}$/", $name); // TRUE! Between 2-50 letters
<?php
if($a && $b) {
die("Won't be visible, because $a and $b are not the same");
}
And second:
$name = '';
$a = !$name; // TRUE! You're variable is empty, but you neg it
$b = preg_match("/^([\w]){2,50}$/", $name); // FALSE! has 0 letters
if($a && $b) {
die("Won't be visible, because $a and $b are not the same");
}
So, you should use OR instead of AND or just forget about first statement (second is checking same thing!):
<?php
if(!preg_match("/^([\w]){2,50}$/", $name)){
$error = ' * Please enter a valid name';
}
You're getting that undefined variable notice because you're trying to echo something in your form that hasn't already been set/not empty and your PHP/HTML form are used in the same file.
Sidenote: <?= is short tag syntax for "echo".
So change:
<?= $error ?>
to and with a conditional statement:
<?php if(!empty($error)) { echo $error; } ?>
or:
<?php if(isset($error)) { echo $error; } ?>
Or use a ternary operator:
http://php.net/manual/en/language.operators.comparison.php
or add an else to my suggestion above.
Plus, you also have a missing brace in your PHP (least, for what you posted) and that alone should have thrown you an unexpected end of file error.
Edit:
The reason that it is failing is the operator you're using, being && (AND). Use || (OR), to check if either one failed the criteria and not both. You're checking if there's no name AND if there's enough valid characters.
if( !$name || preg_match("/^([\w]){2,50}$/", $name))
and that's all it was, a simple wrong choice of operator.
Btw, my edit wasn't based on the other answer given. I actually was busy testing this out when that was posted.
Their explanation is well-written/explained, however they're working too hard.
Changing && to || in your code would have worked just fine.

Categories