Having an issue with PHP elseif code crashing script - php

I'm having an issue when I enable the code below that it is causing my code to crash. I can't figure out where its crashing but I know if I comment out this portion that it will allow the code to run, just not have the checks ran on the other portions of the form.
if (empty($_POST["SCreq"])) {{
$SCreqERR = "SC requires a Yes or No answer";
} else {
$SCreq = test_input($_POST["SCreq"]);}
// elseif($SCreq = "Yes"; $Email=False)
// $EmailERR = "Email is required for SC"
// elseif ($SCreq = "Yes"; $emaildist1 = "")
// $emaildist1ERR = "First Email Distrobution Group required with SC"
// else {
// $emaildist1 = test_input($_POST["emaildist1"])
}}
Any help would be greatly appreciated, I have everything name, and all is the correct case.

The double-quotes basically start a new block within your "if" block. So, your code could be written like this:
if (empty($_POST["SCreq"])) {
{
$SCreqERR = "SC requires a Yes or No answer";
}
else {
$SCreq = test_input($_POST["SCreq"]);
}
}}
Not only are the brackets unbalanced (there's more closing brackets than opening brackets), the "else" also starts inside the "if" block. Removing the {} inside the "if", you get
if (empty($_POST["SCreq"])) {
else {
$SCreq = test_input($_POST["SCreq"]);
}
}}
which isn't valid (the "else" has to come directly after the "if" block, not within it).
Use proper indenting to catch those mistakes quickly. After each "{", start a new line, and indent your code more. After each "}", start a new line, and indent less. After each block, you need to be at the same indent-level as you were before, otherwise you have extra "{"s or "}". You can either do that manually, or have a good editor that does it for you. This kind of code uses proper indenting, and would be valid:
if (empty($_POST["SCreq"])) {
$SCreqERR = "SC requires a Yes or No answer";
}
else {
$SCreq = test_input($_POST["SCreq"]);
}

Use an IDE to help check that things are nested correctly. Hard to tell with things commented out though but... {{. Also, error logs!
I assume you looked at the documentation? http://php.net/manual/en/control-structures.elseif.php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}

elseif($SCreq == "Yes" && $Email == False)
$EmailERR = "Email is required for SC";
elseif ($SCreq == "Yes" && $emaildist1 == "")
$emaildist1ERR = "First Email Distrobution Group required with SC";
else {
$emaildist1 = test_input($_POST["emaildist1"]);}
Condition test is ==
multiple AND condition put &&.
End your statements with ;

Related

How to have an else statement after a loop with an if statement?

I am trying to make a registration system with text files and I need help with using an else statement after the loop that checks if the username is taken.
I am generally just trying to find out how to have an else statement after a loop with an if statement, if I find out that out my problem is basically solved. Here is the code:
while($i < count($logindata)-1) {
if ($_POST['username'] == $user[$i]['username']) {
set_message(" That username is taken", "danger");
}
$i++;
}
else {
if (!empty($_POST['username']) && !empty($_POST['password'])) {
file_put_contents('logininformation.txt', $_POST['username'] . "?=%&$##[}[}+-789409289746829" . $_POST['password'] . "\n", FILE_APPEND);
set_message("Account created!", "success");
} else {
set_message(" You have not put in a username and/or password","danger");
}
}
I expect to be able to have an else statement after the loop and it working.
A loop is not a condition, therefore it does not have an else part either. It is correct that the loop runs while the condition evaluates to true, but as soon as the condition does not evaluate to true, the loop is ended.
Therefore, to check whether the loop was not triggered at all, you have to find a different way, e.g. write a condition on its own.
For the sake of argument, you COULD save a flag and evaluate that afterwards, but in most cases I would not recommend that:
$i = 0;
$loopDidRun = false;
while ($i < 10) {
$i++;
$loopDidRun = true;
}
if (!$loopDidRun) {
echo "loop did not run, therefore the 'else case', but not really";
}
Your logic is severely flawed.
$failed=false;
if(empty($_POST['username']) || empty($_POST['password'])){
$failed=true,
set_message(" You have not put in a username and/or password","danger");
}else{
while($i<count($logindata)-1){
if($_POST['username']==$user[$i]['username']){
$failed=true;
set_message("That username is taken","danger");
break;
}
$i++;
}
}
if(!$failed){
file_put_contents('logininformation.txt',$_POST['username']."?=%&$##[[}+-789409289746829".$_POST['password']."\n",FILE_APPEND);
set_message("Account created!","success");
}
However all I am doing here is fixing bad code. Before anything you need to filter the $POST input given to disallow just any input, passwords etc. should not be stored in plain text, and this is not the proper way of creating a factory for this. You should find better, and secure, examples online and work from them.

Using "or" correctly in PHP with an if statement

I want to check if either of these checkboxes are checked and if either of them are i want the new assigned variable $open_monday to = "yes else "no".
if (isset($_POST['open_monday_lunch'] or $_POST['opening_monday1'])) {
$open_monday = "yes";
}
else { $open_monday = "no"; }
Is that the right way to do it? I have never used or before. I just get a blank pag when trying to run it as if the syntax is incorrect.
Due to Operator precedence its always preferable to use && instead of and ,similarly || instead of or.please refer this link for additional info,
so try like this,
if (isset($_POST['open_monday_lunch'] ) || isset( $_POST['opening_monday1'])) {
$open_monday = "yes";
}
else { $open_monday = "no"; }
You can check it with -
if (!empty($_POST['open_monday_lunch']) || !empty($_POST['opening_monday1'])) {

Search not working as intended

Why won't my search function ever execute the "else" (else should echo a text when no resulsts haved been found)? I also have some problems when trying to show all results (with no search criterias selected, just by pressing the search button). I'll upload the whole code of the page because I don't know if you need the HTML part as well or not to figure out the problem. I know it's a big chunk of code but please help out if you can. Thanks!
Here's a link to my code: http://pastebin.com/BXe1C0dr
This is not yet the answer, just a brief code structure of Matei Panchios code. Because it is hard to make sense of long code, so I try to simplify it so that other people might be able to help.
$termeni = mysql_real_escape_string($_POST['termeni']);
$tip=$_POST['tip'];
$judet=$_POST['judet'];
if((!empty($termeni)) and (isset($tip)) and (isset($judet))) {
$query = "SELECT * FROM oferte WHERE localitate LIKE '%$termeni%' AND
tip_locatie='$tip' AND judet='$judet'";
// do the query and write some HTML
} elseif (isset($tip)) {
$query = "SELECT * FROM oferte WHERE tip_locatie='$tip'";
// do the query and write some HTML
} elseif (isset($judet)) {
$query = "SELECT * FROM oferte WHERE judet='$judet'";
// do the query and write some HTML
} elseif (!empty($termeni)) {
...
} elseif (!empty($termeni) AND (isset($judet))) {
...
} elseif (!empty($termeni) AND (isset($tip))) {
...
} elseif ((isset($judet)) AND (isset($tip))) {
...
} elseif ((!isset($judet)) AND (!isset($tip)) AND (empty($termeni))) {
...
} else {
// I believe this where it does not get executed.
}
Well, it makes sense why it does not get executed because there is other way that the elseif does not cover. If you look from this point of view
If three variable is set
if((!empty($termeni)) and (isset($tip)) and (isset($judet))) {
If two variables is set
elseif (!empty($termeni) AND (isset($judet)))
elseif (!empty($termeni) AND (isset($tip)))
elseif (!empty($termeni) AND (isset($tip)))
elseif (!empty($termeni) AND (isset($tip)))
If one variable is set
elseif (isset($tip))
elseif (isset($judet))
elseif (!empty($termeni))
When no variable is set
elseif ((!isset($judet)) AND (!isset($tip)) AND (empty($termeni)))
which leave else condition with nothing to cover.
If I were you, I would structure the code as following.
if (!empty($termeni) and isset($tip) and isset($judet)) {
query = '....';
} elseif (!empty($termeni) and isset($judet) {
query = '....';
} // .... the rest of the condition
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
// write HTML table
} else {
// write message that there is no result found
}
This will reduce the size of your code by 6 times.

Replacement for nested IF's?

Sometimes mostly for processing user input i find myself using a lot of IF statements nested in each other, sometimes it is much more than below, to the point it goes from if on left side of screen to the if number 10 on right side of screen.
This is very difficult to read and troubleshoot, is there other way to do nested if?
I know about switch() however in this case i have to do query in third if rather than first.
if (true) {
if (true) {
if (true) {
...
echo "You are logged in";
} else {
echo "login failed"
}
} else {
echo "incorrect email";
}
}
I assume that your true conditions are real conditions, and not just the true boolean constant.
if (condition1 && condition2 && condition3) {
echo "You are logged in";
} else {
echo "login failed";
}
If you need a condition handled separately:
if (emailAddressIsCorrect) {
if (condition2 && condition3) {
echo "You are logged in";
} else {
echo "login failed";
} else {
echo "incorrect email";
}
Or you can just return early, which is cleaner in my opinion. You can do this for each condition, if you like. You can have as many conditions as you want with this arrangement, without requiring condition nesting:
if (!emailAddressIsCorrect) {
echo "incorrect email";
return;
}
Often times I'll do the "fail out" strategy instead:
function login() {
if (!condition1) {
echo "incorrect email";
return false;
}
if(!condition2) {
echo "incorrect password";
return false;
}
if(condition3) {
echo "logged in successfully!";
return true;
}
return false;
}
This example is suspect, there are security concerns with letting an attacker know which part of the login failed, but as a code snippet, you can see the strategy.
Combine 2 if statements using "&&".
OR
Sometimes using object oriented programming you can avoid if statements:
if(is type a) {
dostuff1();
} else if(is type b) {
dostuff2();
}
With classes and inheritance:
class->dostuff();
You can also use "first class functions" to avoid if statements.
Say you have values $_POST['page'] == 'page1', $_POST['page'] == 'page2'
$functions = array("page1"=>$function1, "page2"=>$function2);
function dostuff1() {
return 'a';
}
function dostuff2() {
return 'b';
}
$function1 = "dostuff1";
$function2 = "dostuff2";
$functions[$_POST['page']]();
instead of
if($_POST['page'] == '1') dostuff1();
etc... although this method is somewhat scary... lol
compare this:
if ($true1) {
if ($true2) {
if ($true3) {
...
with this:
if ($true1 && $true2 && $true3) {
...
}
with the first appoach not only you're wasting useful space for a single IF,
you are also delaying the inevitable: the optimization at a later day.
Also, it has no matter (etc. performance) if you place your IFs as nested or
in a single line because PHP intepreter will stop checking beyond if it finds
a FALSE.

PHP If/ Else statement not working. Just following 'IF' line

As simple as it seems, I dont know why this isn't working.
I have a form with a few drop down selects that if $message_type is equal to other, the message is constructed out of just the details from $details.
If $message_type is anything else, it should string together a message.
The variables are being passed and have checked that it is exactly 'Other' that is being passed through to the page using echo's so there is no spelling mistake.
At the moment, whatever the message type, it always just creates the message to be just $details and does not follow the 'else' line if it does not equal 'Other'.
if ($message_type = 'Other'){$message = $details;
}
else {$message = "Action to do: ".$message_type." On ".$user." Extra Details: ".$details;
}
Any help as this is now really confusing me.
Thanks
if ($message_type == 'Other')
{
$message = $details;
}
else
{
$message = "Action to do: ".$message_type." On ".$user." Extra Details: ".$details;
}
$message_type = 'Other' is alway true
What you did wrong were already explained by the other answer, but "why" does this happen? It's simple: = is the assignment operator and like any other operator in PHP (and many (all?) languages) the operator has a retun value, that is in this case the value of the assignment. PHP now cast this to a boolean and therefore it is true
if ($message_type = 'Other'){ /* .. */}
if ('Other'){ /* .. */}
if (true){ /* .. */}
if ($message_type = 'Other'){$message = $details;
}
else {$message = "Action to do: ".$message_type." On ".$user." Extra Details: ".$details;
}
you have if ($message_type = 'Other')
you should have if ($mesage_type == 'Other')
I suppose it is just writing mistake, so I wont be telling what is the diferance :)
You need two equal signs
if ($message_type == 'Other') {
-------------------^
$message = $details;
} else {
$message = "Action to do: ".$message_type." On ".$user." Extra Details: ".$details;
}
One equal sign is the assignment operator, so you are saying "$message_type is equal to 'Other'" instead of "if $message_type is equal to 'Other'"

Categories