Validating an if statement with two conditions - php

I'm trying to validate a form. The form has a simple if statement. What is wrong with this please? The browser says: Parse error: syntax error, unexpected '&&' . Both the variables being checked are separate fields. They must both be numbers & not empty.
if (isset($_POST["submit"])) {
if(empty($numberwelds)) && (empty($conwelds)) {
echo " One or both of the numbers are empty ";
} else if(!is_numeric($numberwelds)) && (!is_numeric($conwelds)) {
echo "Data entered was not numeric";
} else {
echo "it passed";
}
}
I'm still getting ' one or both of the numbers are empty', even if they both are numbers. My new code:
if (isset($_POST["submit"])) {
if(empty($numberwelds) || empty($conwelds)) {
echo " One or both of the numbers are empty ";
} else if(!is_numeric($numberwelds) || !is_numeric($conwelds)) {
echo "one or both of them is not a number";
} else {
echo "it passed";
}
}
Thank-you

Your problem is on the lines where you have;
if(empty($numberwelds)) && (empty($conwelds)) {...
and,
} else if(!is_numeric($numberwelds)) && (!is_numeric($conwelds)) {
you are basically trying to create an if statement of the form;
if(stuff in here) && (stuff in here){..
This is a syntax error because if statements need to be followed immediately by a bracketed control flow, and in your example you have an if statement followed by &&.
All you need to do is add some more brackets to make a correct if statement, for example;
use
if((stuff in here) && (stuff in here)){...
instead of
if(stuff in here) && (stuff in here){..

If you want your error output One or both of the numbers are empty to be accurate, you have to use || and not &&
What's happening is even if one of the options is empty, the if statement is ignored. And && means both statements must be true. An || means the either-or OR both must be true.
As far as the syntax error, the other answered solved it for you.

Related

Strugling with if, empty, and, or,

The following script should create an error when date_enabled is 2 and one of the three variables is empty. When day is empty for example, the script still doesn't echo the sentence.
Does anybody sees the problem?
$year = $_POST['date-year'];
$month = $_POST['date-month'];
$day = $_POST['date-day'];
$date_enabled = 2;
if ((($date_enabled ==2)) && ((empty($year) || empty($day) || empty($month)))){
echo "You didn't enter a valid date";
}
UPDATE - When I perform the following script it echos: its empty its empty (function). Which means that empty and the function isEmpty, which I created because of the advice of #Expert System , also works.
if (empty($day)){
echo "its empty";
}
if (!isset($day)){
echo "its not set";
}
if (isEmpty($day)){
echo "its empty (function)";
}
UPDATE AGAIN - The script above works indeed correctly. The problem lays with my form. It works fine now and thanks for your help.
I believe the definition of "empty" in your question is unclear. If empty in your question means zero-length string, then empty function is not the right one for you.
empty() definition from PHP doucment
Determine whether a variable is considered to be empty. A variable is
considered empty if it does not exist or if its value equals FALSE.
empty() does not generate a warning if the variable does not exist.
Maybe this custom function will work in your context
function isEmpty($var) {
return !isset($var) || ($var == '');
}
Then
if (($date_enabled == 2) &&
(isEmpty($year) || isEmpty($day) || isEmpty($month))){
echo "You didn't enter a valid date";
}
Try this code instead:
$year = isSet($_POST["date-year"]) ? $_POST["date-year"] : "";
$month = isSet($_POST["date-month"]) ? $_POST["date-month"] : "";
$day = isSet($_POST["date-day"]) ? $_POST["date-day"] : "";
$date_enabled = 2;
if ((($date_enabled ==2)) && ((empty($year) || empty($day) || empty($month)))){
echo "You didn't enter a valid date";
}
The problem might be the error of level E_NOTICE raised when you try to access an undefined index in $_POST array.
This shoukd notcause a problem (i.e. stop execution) with theususl/default configuration options, but with yours it might (just guessing).

PHP Multiple condition if statement returning nothing

I have been trying to figure this out for weeks, it is a simple statement yet it never executes the if statement. I'm echoing the variables to the screen so I know they exist and each condition is true, but the echo "something" never executes.
if ($db_a==$session_a && $db_b==$session_b && $dbfreq_b=="1")
{
echo "something";
}
I thought it was just the brackets as I had this originally:
if (($db_a==$session_a) && ($db_b==$session_b) && ($dbfreq_b=="1"))
I am comparing variables stored in a MYSQL database with session variables.
If I use Var_dump the db variables are null, yet they echo the expected string value to the screen.
$db_a="username";
$session_a="username";
$db_b=="keyword string"; -mostly one word but could be multiple
$session_b=="keyword string";
$dbfreq_b="1"; - This is the frequency that the keyword appears in the MYSQL database
using vardump $db_a and $db_b are NULL yet they echo what I am expecting to see to the browser.
Hopefully this explains things a bit more?
Thank you for the very prompt help!!
If as you say $db_a = $session_a AND $db_b = $session_b AND $dbfreq_b = 1 then it's impossible that condition returns false.
Please check your code again (all 5 variables) and make sure ALL of the conditions are met.
You could just split your single IF into three separate conditions so that you know which one returns false.
if ($db_a == $session_a) {
echo "first OK\n;"
}
if ($db_b == $session_b) {
echo "second OK\n";
}
if ($dbfreq_b == "1") {
echo "third OK";
}
Could you add the values of your variables to your question?

Placement of Else in a nested If

I am a PHP noob working through the tutorials and I found an issue with nested If Else that I don't understand. I have an outer if with a series of inner if's. And, I have an else I wanted associated with the outer if. My original code never executed the else, which should occur if the outer if was false. The original code was:
if (!($result["name"] & $result["age"] & $result["email"]))
{
if (!$result["name"])
{
echo("Name must be supplied.<br>");
}
if (!$result["age"])
{
echo("Age must be a number between 1 and 120.<br>");
}
if (!$result["email"])
{
echo("E-Mail is not valid.<br>");
}
}
else
{
echo("User input is valid.<br/>");
}
As I said, the else was never executed. However, I moved the else inside the brackets and it worked. The working code is:
if (!($result["name"] & $result["age"] & $result["email"]))
{
if (!$result["name"])
{
echo("Name must be supplied.<br>");
}
if (!$result["age"])
{
echo("Age must be a number between 1 and 120.<br>");
}
if (!$result["email"])
{
echo("E-Mail is not valid.<br>");
}
else
{
echo("User input is valid.<br/>");
}
}
This seems to be wrong to me. Probably just some noob mistake but I cannot figure it out. Thanks for your help...RG
Use AND comparison operator or && comparison operator instead of & bitwise operator.
For a quick review of PHP operators go here
Replace this:
if (!($result["name"] & $result["age"] & $result["email"]))
with this
if (!($result["name"] && $result["age"] && $result["email"]))
Its two & signs not only one.
on your first if . if you want to execute it
if your name,age and email is empty or not set
you need atleast to put ! on every $result[] and change your & to &&
if (!($result["name"] && !$result["age"] && !$result["email"]))
try to use this code..

string comparison in php

I am trying to compare two strings I get from a password form in HTML.
They are being stored in variables from $_POST. I print them out and they look the same, but the code below will never evaluate to true, only false. Why does that happen?
//Verify the passwords match
if( ($passwd != $pass_confirm) && ($new_email != $email_confirm) ){
echo "Email and/or password do not match";
return FALSE;
}
I appreciate any help.
For your code to show the error message, both the email and password must be wrong.
Try using || instead of &&, so the error is shown when just one of them is wrong.
If you print them out and they look the same, you might have a trailing newline character problem. Perhaps you could try trimming the strings before comparison? Doing a var_dump might help to pinpoint the problem because it shows the length of the string.
Also, I would suggest the following check (note the || and strict comparison operators):
if ($passwd !== $pass_confirm || $new_email !== $email_confirm) {
echo "Email and/or password do not match";
return false;
}

Programmimg Logic

Am new to the world of coding and have difficulty is understanding the logic below. Appreciate it if someone could explain it to me. Let me start off with If statements.
/* Sample Code */
if($username == "123") {
//some code here;
}
if ($username == "abc") {
//some code here;
}
My understanding is that IF the first statement fails, progress to the second statement i.e. if $username does not equal to 123 then test whether it is abc. Is that correct?
Now, let me expand on that same code with else statements
/* Sample Code */
if($username == "123") {
//some code here;
}
if ($username == "abc") {
//some code here;
}
else {
//some code here;
}
My understanding is that IF the first staement FAILS i.e. $username does not equal to 123 then test the second statement. IF the second statement fails i.e. $username does not equal to abc then proceed to ELSE which is a catchall should all preceding IF statements FAIL. Is that correct?
Let me expand on that again using ELSE IF statements
/* Sample Code */
if($username == "123") {
//some code here;
}
else if ($username == "abc") {
//some code here;
}
else {
//some code here;
}
How is this code different from 2 separate if statements? What does ELSE do in the entire block of code?
the difference between:
if() {
}
else if() {
}
and
if() {
}
if() {
}
is that the second condition in the second example is always tested, regardless of the first if condition. In the first example, the second clause only executes if the first clause is false.
In your example, since "123" is never equal to "abc", they are equivalent. In real life, the ifs don't need to be related:
if (a) {
// Do something
} else if (b) {
// Do something else
} else {
// Do something else
}
is different from
if (a) {
// Do something
}
if (b) {
// Do something else
} else {
// Do something else
}
In the second case, both a and b might be true, in which case both lines will fire. In the first case, only the first line will fire, since the else will never even be read.
In this case they are the same:
if($username == "123") {
//some code here;
}
if ($username == "abc") {
//some code here;
}
against
if($username == "123") {
//some code here;
}
else if ($username == "abc") {
//some code here;
}
The difference is that with else if if the first case is true the second case will never fire.
e.g.
if($username == "123") {
//some code here;
$username = "abc"
}
if ($username == "abc") {
//some code here;
}
Both code if statement code blocks will be executed where as in:
if($username == "123") {
//some code here;
$username = "abc"
}
else if ($username == "abc") {
//some code here;
}
only the first if statement code block will be executed.
You aren't right, here's how it works:
if($something == "something")
{
//code
}
if($something == "somethingelse")
{
//code
}
Both of the above will be tested regardless of what $something equals, because they are two separate if statements. So if you were to do:
$something = "something";
if($something == "something")
{
echo $something;
}
$something = "somethingelse";
if($something == "somethingelse")
{
echo $something;
}
then the output would be "somethingsomethingelse" because both are tested. Note that in an if/elseif/else structure, it would be a syntax error to put a line of code between the ending of one block and the beginning of another.
if($something == "something")
{
//code
}
else
{
//code
}
In this, the first statement will be tested, if it is true, then it will run through that code. If false, then the code in the else block will occur.
if($something == "something")
{
//code
}
elseif($something == "somethingelse")
{
//code
}
else
{
//code
}
In this it would check the first if statement, if true, then that code runs. If false, it checks the elseif statement, if true it runs that. If false it runs the else block. The else block is a catch all.
So in something like:
if(false)
{
//code
}
elseif(false)
{
//code
}
else
{
//code
}
the else block will always be run.
The same sort of thing occurs in multiconditional statements such as:
if(is_string($something) && $something == "something")
if is_string($something) is false, it won't check the second condition because they both must be true when AND is used, and if is_string($something) is true and $something == "something" is false, then the entire if condition is false, yet again because they both must be true.
if($something == "something" || $something == "somethingelse")
In this OR statement, it will check both if the first is false, because one or the other must be true in order for the if statement to be true. So if $something does equal "somethingelse" then the if statement will be considered true. However, if $something does equal "something" then the second condition won't be checked, because it already got the true condition it needs to make the statement true.
So an && condition in an if condition is like doing:
if(is_string($something))
{
if($something == "something")
{
//code
}
}
and and || statement is like doing:
if($something == "something")
{
//code
}
elseif($something == "somethingelse")
{
//same code as previous if statement
}
Here is an example:
//this would be pulled from a page called like:
//http://www.domain.com/page.php?num=5&num2=10
$num = $_GET['num']; //5
$num2 = $_GET['num2']; //10
if(!is_numeric($num))
{
echo 'Number 1 is not a number, cannot continue <br />';
}
elseif(!is_numeric($num2))
{
echo 'Number 2 is not a number, cannot continue <br />';
}
else
{
if($num > $num2)
{
echo 'Number 1 is bigger than Number 2 <br />';
}
elseif($num2 > $num)
{
echo 'Number 2 is bigger than Number 1 <br />';
}
else
{
echo 'Numbers are equal <br />';
//Since if the numbers are neither greater than or less than each other, they must be equal to one another
}//end if
//% is the modulo operator, basically returns the remainder of division
//so !($num % $num2) is if the remainder of $num / $num2 == 0, I.E. NOT(!) $num % $num2
//! basically makes it take the opposite of the result, so !(0) is true, and 0 is false
//in the same way !(true) is literally NOT true (in other words false)
//and !(false) is literally NOT false (true)
if(!($num % $num2))
{
echo 'Number 1 is a multiple of Number 2 <br />';
}
else
{
echo 'Number 1 is not a multiple of Number 2 <br />';
}//end if
if(!($num2 % $num))
{
echo 'Number 2 is a multiple of Number 1 <br />';
}
else
{
echo 'Number 2 is not a multiple of Number 1 <br />';
}//end if
echo 'The sum of the numbers is ' . $num + $num2;
}//end if
So, with this, and an input of num=5&num2=10, the output would be
Number 2 is bigger than Number 1
Number 1 is not a multiple of Number 2
Number 2 is a multiple of Number 1 //Note that both of the multiple conditions were tested, because they are separate
The sum of the numbers is 15
With this an an input of num=16&num2=3, the output would be:
Number 1 is bigger than Number 2
Number 1 is not a multiple of Number 2
Number 2 is not a multiple of Number 1
The sum of the numbers is 19
and with an input of num=16&num2=word, the only output would be
Number 2 is not a number, cannot continue
and with an input of num=4&num2=4 the output would be
Numbers are equal
Number 1 is a multiple of Number 2
Number 2 is a multiple of Number 1
The sum of the numbers is 8
My understanding is that IF the first
statement fails, progress to the
second statement i.e. if $username
does not equal to 123 then test
whether it is abc. Is that correct?
This isn't correct. Both expressions will be evaluated; however, at most one of them can be true. Your third example behaves the way you describe above.
In your second example, if $username == "123", then the block associated with the first if statement will execute; however, the "else" block associated with the second if statement will also execute.
In the first example, both "if" statements are executed. If both are true, both happen.
In your case, both can't be true, but that's no reason not to use "else". If nothing else [no pun intended], "else" will provide a semantic hint for future programmers that you're only expecting one of the two clauses to be true.
The only way for your statement:
IF the first statement fails, progress to the second statement
to be true is if the second statement was indeed in an "else" clause of the first statement.
Only in the last snippet does the code behave as you describe. When you have an if followed by a second if, both tests are performed. There is no symbiosis or relation in the code flow.
if(X1){
A;
}elseif(X2){
B;
}elseif(X3){
C;
}else{
D;
}
this means: if X1 evaulates to true then do A. If not look if X2 evaluates to true. if yes do B. if not look if X3 evaluates to true. if so do C. if not then just do D.
if(X1){
A;
}
if(X2){
B;
}
this means: if X1 evaluates to true do A. end of your first if. then another if comes: if X2 evaluates to true then do B. these two if statements are separated from eachother unlike my first example.
the alternative if syntax in php makes it a bit clearer:
My first example in alternative syntax:
if(X1):
A;
elseif(X2):
B;
elseif(X3):
C;
else:
D;
endif;
my second example:
if(X1):
A;
endif;
if(X2):
B;
endif;
here you see clearly that these two if statements are separated from eachother.

Categories