siwelis Posted July 1, 2010 Share Posted July 1, 2010 For some reason I have some code like this that executes even when the variable isn't set. Is my syntax wrong? $setting = mysql_real_escape_string($_POST['setting']); //value posted for setting is "yes" if($setting = "correct"){ echo Hello; } //echo's Hello //works right ////OTHER SCENARIO $setting = mysql_real_escape_string($_POST['setting']); //value is not posted for setting if($set = "yes"){ echo Hello; } //Still echo's Hello I know I could just do a check to see if the variable is set and if not exit() or similar, but I really shouldn't have to... right? I don't mind workarounds, but I'd rather work it through. Link to comment https://forums.phpfreaks.com/topic/206409-code-executed-when-it-shouldnt-be/ Share on other sites More sharing options...
PFMaBiSmAd Posted July 1, 2010 Share Posted July 1, 2010 One = sign is an assignment operator. Two == signs is a comparison operator. So, yes, your variables are set, with the value on the right-hand side of the = sign, and the if() statements are true at that point. Link to comment https://forums.phpfreaks.com/topic/206409-code-executed-when-it-shouldnt-be/#findComment-1079773 Share on other sites More sharing options...
KevinM1 Posted July 1, 2010 Share Posted July 1, 2010 The '=' is the assignment operator. You want to use '==' in conditionals for equality. Link to comment https://forums.phpfreaks.com/topic/206409-code-executed-when-it-shouldnt-be/#findComment-1079774 Share on other sites More sharing options...
Pikachu2000 Posted July 1, 2010 Share Posted July 1, 2010 Yes, the syntax is wrong. You're performing an assignment, rather than a comparison. if( $setting = 'correct' ) has no problem assigning 'corect' to setting, therefore always evaluates as true. if( $setting == 'correct' ) will compare the values. Link to comment https://forums.phpfreaks.com/topic/206409-code-executed-when-it-shouldnt-be/#findComment-1079775 Share on other sites More sharing options...
siwelis Posted July 1, 2010 Author Share Posted July 1, 2010 if( $setting = 'correct' ) has no problem assigning 'corect' to setting, therefore always evaluates as true. LOL! I'm glad PHP has no problem with that! - Thanks a lot guys! This clears up a LOT of issues I've had. Link to comment https://forums.phpfreaks.com/topic/206409-code-executed-when-it-shouldnt-be/#findComment-1079787 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.