Stuck Troubleshooting Compound IF Statement - php

I am experienced programmer, but am not a PHP developer. I have been asked to troubleshoot the following code, but can't see what the problem is. This IF statement works:
<?php
if ($ice_cream_social == 'yes') {
$registration_price = "58.00";
}
?>
However, the page in question requires some compound IF statements to test if form elements have been checked and adjust the price accordingly. This code does NOT work, it doesn't give an error -- but the IF doesn't execute:
<?php
if ($ice_cream_social == 'yes' AND $registration_type == 'Banquet and Conference') {
$registration_price = "78.00";
?>
Using developer tools I have verified the form fields are being passed from the HTML, the code has the variable name and value spelled correctly, and I can test for any ONE variable's value successfully. It seems that when a second or third test is added using the syntax I showed above, the test fails and the IF doesn't run. Based on my limited understanding of PHP's syntax and some Googling, the code looks correct to me (and does not produce any errors), but I am thinking I am missing something about why this isn't working.
Can someone tell me if I'm missing something obvious in my code sample that would cause the IF not to run? I didn't include more code as this is one piece of a messy set of includes :)
Thanks!

It looks like to me on the elseif you don't have a logical check, so you either need to change it to else or add a check(if that is your intention) elseif($registration_price>0)
I used this code to test:
<?php
$registration_price = '';
$ice_cream_social = 'yes';
//$ice_cream_social = 'no';
$registration_type = 'Banquet and Conference';
//$registration_type = 'Something else';
if ($ice_cream_social == 'yes') {
$registration_price = "58.00";
} else {
$registration_price = "not defined";
}
echo $registration_price;
if ($ice_cream_social == 'yes' && $registration_type == 'Banquet and Conference') {
$registration_price = "78.00";
} elseif( 1 > 0) {
$registration_price = "1 million dolars!";
} else {
$registration_price = "not defined";
}
echo $registration_price;

Related

whitespace error in PHP, expecting an identifier

Not sure what should be the title for this case, please edit if you have a suitable title for it. See below for the exact question.
MySQL Database:
Now I want to check if the value option in "Right_Option" is having value or not. (As per above, it is not having as Right_Option is "C" & Option_C is not having any value.)
My Code:
$option = "$row['Option_".$right_option."'];";
if($option != ''){
//Other Codes
}
else{
//other codes
}
It gives me an error:
You are using it wrong. Use this instead:
if(isset($row["Option_".$right_option]) && $row["Option_".$right_option] !== ''){
//Other Codes
}
else{
//other codes
}

Real estate site, trying to only output properties based on type

So I inherited an old site from another developer, and I'm not really a programmer so I'm having some trouble. I've put the code into a Fiddle: https://jsfiddle.net/s6coraf5/
Basically there are different categories of real estate properties and when you click on different pages it's supposed to filter them and only display the ones specific to whatever page you're on. The problem is that no matter what page you're on, it's just displaying everything. I've narrowed down some specific code but can't figure out why it isn't applying it right.
In the php there's:
$select_title = "Unknown";
if ($select_type == "all") { $select_title = "All Listings"; }
if ($select_type == "office") { $select_title = "Office"; }
if ($select_type == "industrial") { $select_title = "Industrial"; }
if ($select_type == "retail") { $select_title = "Retail"; }
if ($select_type == "shoppingcenter") { $select_title = "Shopping Center"; }
if ($select_type == "land") { $select_title = "Land"; }
if ($select_type == "agricultural") { $select_title = "Ranch / Farm"; }
if ($select_type == "investment") { $select_title = "Investment"; }
if ($select_type == "lodging") { $select_title = "Lodging"; }
if ($select_type == "sportsentertainment") { $select_title = "Sports / Entertainment"; }
In the HTML there are various places where those $select_type's are supposed to be applied:
a href="properties.php?select_type=<?php echo $select_type;?>&select_city=<?php echo $select_city;?>&priceForm=<?= $lowPrice;?>,<?= $highPrice; ?>&sqft=<?= $lowSize;?>,<?= $highSize; ?>&sort_type=city, asking_price desc"><font size=4><b>Location,</b></a>
it's only applying the "all" one though on every page. Again, the fiddle has the full php and html which is probably more helpful. I realize it's ugly and bad but maybe someone can see something obvious that I can't.
Thanks in advance for any help anyone can provide.
Based on the PHP code in the fiddle (Which really shouldn't be there since the fiddle is for Javascript), it seems like the problem is that you never use the select_type given in the URL.
Take a look at this line. This is the first time $select_type is used.
if (!isset($select_type)) $select_type = "all";
Thus, $select_type will always be all.
Instead you should either change it to:
if (!isset($select_type)) $select_type = $_GET['select_type'];
Or just add this line before it:
$select_type = $_GET['select_type'];
Your ssql query in your jsfiddle seems like it might be the culprit. I'll put it here to make it easier:
select properties.property_id,selected_subtypes.property_type,properties.listing_type,properties.city,properties.asking_price,memberships.name,properties.membership_id,properties.building_size,memberships.website,properties.sold_price
from selected_subtypes,properties,memberships where (selected_subtypes.property_id = properties.property_id)
and (properties.membership_id = memberships.membership_id)
and (memberships.status = 'Active') and (properties.sold_information = ' ' or properties.sold_information = 'Undisclosed')
and ((selected_subtypes.property_category ='".$select_type."' or '".$select_type."'='all')
or (selected_subtypes.property_type ='".$select_type."'))
and (properties.city = '".$select_city."' or '".$select_city."'='all')
and (properties.asking_price BETWEEN ".$lowPrice." and ".$highPrice.")
and (properties.building_size BETWEEN ".$lowSize." and ".$highSize.")
".$date_sql."
order by ".$sort_type
The query appears to be, in each line, be selecting $select_type OR 'all
This boolean approach will always bring back either of those, so it would bring back "all" every time.
If you want to bring back only the selected type, you'd need to eliminate the "all" within the OR in these rows.
The easiest way to handle this would be to set the value $select_type to be equal to "all" if that is what is selected, or else, the specific type. One way he way I do "all" queries is to set the value to be "1=1" which will always be true.
In other words, modify the query like so (for each of the selected types) to show this (I changed the OR to AND in this case)
AND selected_subtypes.property_type ='".$select_type."'
and then in the php modify the code to be something like this:
if (!isset($select_type)) {
$select_type = "1=1"
}
else {
$select_type = $_GET['select_type'];
}
Another thing to be aware of
This particular code is somewhat vulnerable to SQL injection, so you might want to modify the way that you query the database. I strongly suggest you look into prepared statements, either using mysqli or PDO

php - issue with booleans in if statement

I have been running into a weird issue for some time with php now and wonder if anybody can help. It's probably a totally minor stupid thing I don't see.
"if" statements don't seem to work for me when I use && and || for logical expressions.
Latest example:
$isNotSet = !isset($moved); // var_dump prints false
$moveSuccess = $moved instanceof SuccessNotification; // var_dump prints true
if(($isNotSet == true) || ($moveSuccess == true)){
the script always breaks at exactly that line and doesn't go any further. It won't execute anything after this.
I have tried lots of things, e.g.
if(!isset($moved) || $moved instanceof SuccessNotification){
or
if(!isset($moved) === true || $moved instanceof SuccessNotification){
or
$isNotSet = !isset($moved);
$moveSuccess = $moved instanceof SuccessNotification;
if($isNotSet === true || $moveSuccess === true){
All don't work. I'm aware they all mean the same, I was just trying to eliminate the thought of being on the wrong track. Some of those examples are marked as syntax error in Netbeans, but not all of them, which got me thinking.
I'd like to know what's going on here because this limits coding a lot. But as I said, I probably overlook a totally simple thing.
edit: the script breaks without any errors or warnings shown, it just stops working at that line
edit2:
I took the snippet and executed it on its own.
$moved = new SuccessNotification($code, $title, $message);
echo 1;
$isNotSet = !isset($moved);
echo 2;
$moveSuccess = $moved instanceof SuccessNotification;
echo 3;
if(($isNotSet === true) || ($moveSuccess === true) || 1){
echo 4;
}else{
echo 5;
}
echo 6;
This prints "123", nothing else. And yes, I have included the SuccessNotification class (otherwise there would have been an error anyways) which is being used system-wide already and properly working, just removed that line for posting here.
I take it that nobody really has a clue and therefore tries to find a simple solution which is ok because I thought it's just a simple thing. But I realize I have tried everything you suggest or would do in this situation.
Shouldnt it be:
if(($isNotSet === true) || ($moveSuccess === true)){
Instead of:
if(($isNotSet == true) || ($moveSuccess == true)){

PHP - Wondering about efficiency of nested IF statements for user registration

I am working on a little project of designing a website for my friends and myself.
I am currently building the user registration system and am wondering if the way I am checking user's entries is the best it could be.
Um, ignore the api stuff, it is for eve and likely irrelevant.
I have plans for the elses.
Essentially, I would like to know if this is acceptable in terms of... everything.
And if not, what could I do to improve this.
I am newer to PHP, please be kind :)
So, this is what I am currently using:
if (!empty($_POST['username'])
&& !empty($_POST['password1'])
&& !empty($_POST['password2'])
&& !empty($_POST['email1'])
&& !empty($_POST['email2'])
&& !empty($_POST['keyID'])
&& !empty($_POST['vCode'])
){
$api = new EVEAPI();
if ($api->getCharacterID($_POST['username']) != 0){
//The username is valid.
if ($_POST['password1'] == $_POST['password2']){
//Passwords match.
if ($_POST['email1'] == $_POST['email2']
&& filter_var($_POST['email1'], FILTER_VALIDATE_EMAIL)
){
//Emails match and are in valid format.
if ($api->isValidAPI($_POST['keyID'], $_POST['vCode'])){
//If the API returns something that is not an error, continue.
$xml = $api->getAPIKeyInfo($_POST['keyID'], $_POST['vCode']);
if ($xml->result->key->attributes()->type == 'Account'){
//If the 'type' of the returned API info is 'Account', continue.
foreach ($xml->result->key->rowset->row as $apiRow){
$charID = (int) $apiRow->attributes()->characterID;
if ($charID == $api->getCharacterID($_POST['username'])){
//DO SOMETHING WITH INFO
}
else{
}
}
}
else{
}
}
else{
}
}
else{
}
}
else{
}
}
else{
}
Efficiency wise this isn't going to matter all that much, but for maintainability's sake it will.
Instead of nesting so many ifs like that, try early failure with your ifs. Something like this:
if ($api->getCharacterID($_POST['username']) == 0) {
// Fail early. Throw an exception, die, or whatever
}
// Continue along as normal, not in an else.
if ($_POST['email1'] != $_POST['email2']) {
// Fail early. Throw an exception, die, or whatever
}
// Etc.
That sort of strategy will generally serve you well unless there's a very good reason to not use it.
It is hard to read and not very clean. The way I do it is use negative if statements. By that I mean the following:
if ($api->getCharacterID($_POST['username']) == 0){
// Username is not valid, so stop execution
}
if ($_POST['password1'] != $_POST['password2']) {
// Send error to user and stop execution
}
// ...etc.
Now how do you stop execution? Well you have few options
Throw an exception
Use die statement
have a parameter that you change everytime you enter an if block, then check if you should continue.
some other solution
But the point is, this approache makes your code cleaner.
Cheers.
These days mostly programmer use jquery / Javascript for forms validations, but if you are using pure PHP the try below code, hope it will be good and secure obviously :)
$username = mysql_real_escape_string($_POST['username']);
if($username == "")
{
$username_required = '<div>Please enter your username</div>';
} else {
$username_ok = true;
}
Typically in most validation patterns out there they have this errors array where you check for all the conditions and add error messages into the array if the array is empty at the end it only means that there are no errors..
For me i wouldn't want my code to look too nested like this i would use variables to dictate each step.
From there you can decide whether to display just the first error. It doesnt hurt to validate through everything at once because the processing should not be that extensive unless you have like 5000 form fields. I think it's ok.
When you code you must remember because code is written for humans and you will want to be kind to your eyes or for those who read your code.. Basically nested is ok. it saves some further processing and it also depends on the logic you need.
Yes its good to save time but at times you do things too nicely to minimize processing you have to weigh the needs if you do it so nice but in the end the time you save is so substantial then it makes no point.. The compiler is not going to pat your back and say good job anyways..
$errors = array();
$usernameValid = $api->getCharacterID($_POST['username']) != 0;
if (!$usernameValid) $errors[] = 'Username is not valid';
//If you want to store which attribute caused the error you can use the attribute name as array key
//if (!$usernameValid) $errors['username'] = 'Username is not valid';
$passwordMatches = $_POST['password1'] == $_POST['password2'];
if (!$passwordMatches) $errors[] = 'Password does not match';
if ($usernameValid && $passwordMatches)
{
//What to do if user name and password passes validation. wooo hoo~
}
//Etc etc..

Any way to break if statement in PHP?

Is there any command in PHP to stop executing the current or parent if statement, same as break or break(1) for switch/loop. For example
$arr=array('a','b');
foreach($arr as $val)
{
break;
echo "test";
}
echo "finish";
in the above code PHP will not do echo "test"; and will go to echo "finish";
I need this for if
$a="test";
if("test"==$a)
{
break;
echo "yes"; // I don't want this line or lines after to be executed, without using another if
}
echo "finish";
I want to break the if statement above and stop executing echo "yes"; or such code which is no longer necessary to be executed, there may be or may not be an additional condition, is there way to do this?
Update: Just 2 years after posting this question, I grew up, I learnt how code can be written in small chunks, why nested if's can be a code smell and how to avoid such problems in the first place by writing manageable, small functions.
Sometimes, when developing these "fancy" things are required. If we can break an if, a lot of nested ifs won't be necessary, making the code much more clean and aesthetic.
This sample code illustrates that in certain situations a breaked if can be much more suitable than a lot of ugly nested ifs.
Ugly code
if(process_x()) {
/* do a lot of other things */
if(process_y()) {
/* do a lot of other things */
if(process_z()) {
/* do a lot of other things */
/* SUCCESS */
}
else {
clean_all_processes();
}
}
else {
clean_all_processes();
}
}
else {
clean_all_processes();
}
Good looking code
do {
if( !process_x() )
{ clean_all_processes(); break; }
/* do a lot of other things */
if( !process_y() )
{ clean_all_processes(); break; }
/* do a lot of other things */
if( !process_z() )
{ clean_all_processes(); break; }
/* do a lot of other things */
/* SUCCESS */
} while (0);
As #NiematojakTomasz says, the use of goto is an alternative, the bad thing about this is you always need to define the label (point target).
Encapsulate your code in a function. You can stop executing a function with return at any time.
proper way to do this :
try{
if( !process_x() ){
throw new Exception('process_x failed');
}
/* do a lot of other things */
if( !process_y() ){
throw new Exception('process_y failed');
}
/* do a lot of other things */
if( !process_z() ){
throw new Exception('process_z failed');
}
/* do a lot of other things */
/* SUCCESS */
}catch(Exception $ex){
clean_all_processes();
}
After reading some of the comments, I realized that exception handling doesn't always makes sense for normal flow control. For normal control flow it is better to use "If else":
try{
if( process_x() && process_y() && process_z() ) {
// all processes successful
// do something
} else {
//one of the processes failed
clean_all_processes();
}
}catch(Exception ex){
// one of the processes raised an exception
clean_all_processes();
}
You can also save the process return values in variables and then check in the failure/exception blocks which process has failed.
Because you can break out of a do/while loop, let us "do" one round. With a while(false) at the end, the condition is never true and will not repeat, again.
do
{
$subjectText = trim(filter_input(INPUT_POST, 'subject'));
if(!$subjectText)
{
$smallInfo = 'Please give a subject.';
break;
}
$messageText = trim(filter_input(INPUT_POST, 'message'));
if(!$messageText)
{
$smallInfo = 'Please supply a message.';
break;
}
} while(false);
goto:
The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label. This is not a full unrestricted goto. The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one. You also cannot jump into any sort of loop or switch structure. You may jump out of these, and a common use is to use a goto in place of a multi-level break...
There exist command: goto
if(smth) {
.....
.....
.....
.....
.....
goto My123;
.....
.....
}
My123:
....your code here....
BUT REMEMBER! goto should not be ever used anywhere in real-world scripts, as it is a sign of poor code.
You could use a do-while(false):
<?php
do if ($foo)
{
// Do something first...
// Shall we continue with this block, or exit now?
if ($abort_if_block) break;
// Continue doing something...
} while (false);
?>
as described in http://php.net/manual/en/control-structures.if.php#90073
No, there is no way to "break" an if block like you would inside loops.:(
So turn your test into a switch !
I wonder why nobody encouraged you to use switch statement since (even if you haven't to many test cases)
Do you think it's too verbose?
I would definitely go for it here
switch($a){
case 'test':
# do stuff here ...
if(/* Reason why you may break */){
break; # this will prevent executing "echo 'yes';" statement
}
echo 'yes'; # ...
break; # As one may already know, we might always have to break at the end of case to prevent executing following cases instructions.
# default:
# something else here ..
# break;
}
To me Exceptions are meant to raise errors and not really to control execution flaw.
If the break behaviour you are trying to set is not about unexpected error(s), Exception handling is not the right solution here :/.
$a = 1;
switch($a) {
case "1":
if ($condition1){
break;
}
if ($condition2){
break;
}
if ($condition3){
break;
}
}
In this way I got what I want. I use a switch only has a definite case and then use break in case to choose if condition. The reason why I use the break : condition1 and condition2 may both satisfy, in that situation only condition1 is applied .IF is selective according the order.
I had the same problem. A solution is to pile if.
The first example is simplistic but...
$a="test";
if("test"==$a)
{
do something
//break; We remove from your example
if(comparison) {
echo "yes";
}
}
echo "finish";
Or, you can use goto.
$a="test";
if("test"==$a)
{
do something
goto the_end_of_your_func;
echo "yes";
}
the_end_of_your_func:
echo "finish";
No.
But how about:
$a="test";
if("test"==$a)
{
if ($someOtherCondition)
{
echo "yes";
}
}
echo "finish";
Just move the code that is not supposed to be executed to else/elseif branch. I don't really see why would you want to do what you're trying to do.
The simple answer is that no, there isn't a way to break from an if statement without completely stopping the execution (via exit). Other solutions won't work for me because I can't change the structure of the if statement, since I'm injecting code into a plugin, like so:
if ( condition ) {
// Code and variables I want to use
// Code I have control over
// Code I don't want to run
}
// More code I want to use
Answering to your question whether that is achievable or not, then yes that is achievable using "goto" operator of php.
But ethically, its not a good practice to use "goto" and of there is any need to use goto then this means that code need to be reconstructed such that requirement of goto can be removed.
According to the sample code you posted above, it can be clearly seen that the code can be reconstructed and the code that is no more required can be either deleted or commented (if possibility is there for use in future).
$arr=array('test','go for it');
$a='test';
foreach($arr as $val){
$output = 'test';
if($val === $a) $output = "";
echo $output;
}
echo "finish";
combining your statements, i think this would give you your wished result.
clean and simple, without having too much statements.
for the ugly and good looking code, my recomandation would be:
function myfunction(){
if( !process_x() || !process_y() || !process_z()) {
clean_all_processes();
return;
}
/*do all the stuff you need to do*/
}
somewhere in your normal code
myfunction();
i have a simple solution without lot of changes.
the initial statement is
I want to break the if statement above and stop executing echo "yes"; or such code which is no longer necessary to be executed, there may be or may not be an additional condition, is there way to do this?
So it seems simple. try code like this:
$a="test";
if("test"==$a)
{
if (1==0){
echo "yes"; // this line while never be executed.
// and can be reexecuted simply by changing if (1==0) to if (1==1)
}
}
echo "finish";
if you want to try without this code, it's simple. and you can back when you want. another solution is comment blocks.
or simply thinking and try in another separated code and copy paste only the result in your final code.
and if a code is no longer nescessary, in your case, the result can be
$a="test";
echo "finish";
with this code, the original statement is completely respected
and more readable!
The simple solution is to comment it out.
$a="test";
if("test"==$a)
{
//echo "yes"; //no longer needed - 7/7/2014 - updateded bla bla to do foo
}
The added benefit is your not changing your original code and you can date it, initial it and put a reason why.
What about using ternary operator?
<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
?>
Which is identical to this if/else statement:
<?php
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
?>
To completely stop the rest of the script from running you can just do
exit; //In place of break. The rest of the code will not execute
I'm late to the party but I wanted to contribute. I'm surprised that nobody suggested exit(). It's good for testing. I use it all the time and works like charm.
$a ='';
$b ='';
if($a == $b){
echo 'Clark Kent is Superman';
exit();
echo 'Clark Kent was never Superman';
}
The code will stop at exit() and everything after will not run.
Result
Clark Kent is Superman
It works with foreach() and while() as well. It works anywhere you place it really.
foreach($arr as $val)
{
exit();
echo "test";
}
echo "finish";
Result
nothing gets printed here.
Use it with a forloop()
for ($x = 2; $x < 12; $x++) {
echo "Gru has $x minions <br>";
if($x == 4){
exit();
}
}
Result
Gru has 2 minions
Gru has 3 minions
Gru has 4 minions
In a normal case scenario
$a ='Make hot chocolate great again!';
echo $a;
exit();
$b = 'I eat chocolate and make Charlie at the Factory pay for it.';
Result
Make hot chocolate great again!
$a="test";
if("test"!=$a)
{
echo "yes";
}
else
{
echo "finish";
}

Categories