Jump to content


Photo

if statements and Variables


  • Please log in to reply
2 replies to this topic

#1 chrisbcats

chrisbcats
  • Members
  • PipPip
  • Member
  • 11 posts

Posted 06 June 2006 - 08:48 PM

I'm trying to validate a form before saving the input to MySQL. Here is a sample of what I'm doing.


if(isset($_POST["create"])) {

if((!$_POST['uname']) | strlen($_POST['fname']) < 2 ) { 
        $print_again = true;  
    }
    
if((!$_POST['passwd']) | strlen($_POST['passwd']) < 3 ) { 
        $print_again = true; 
    }

if($print_again) { 
//do nothing
}
else{
echo('everything is good');
}
}

What shold happen is:
If the variable is invalid, $print_again is set to true, and nothing changes. But if the variable is valid then a messages appears on the screen.

What really happens:
After the variable is set to true once it is always true. How can I fix this since this code is in a submit button? I've tried $print_again = false; before the if statements, but then $print_again is always set to false.

#2 Koobi

Koobi
  • Staff Alumni
  • Advanced Member
  • 419 posts
  • LocationColombo, Sri Lanka | South Asia

Posted 06 June 2006 - 09:40 PM

hmmm is your intention to check if $_POST['uname'] is empty OR $_POST['fname'] is longer than 2 characters in th first if condition?

if that's the case, consider using || instead of |
|| is a logical OR, | is a bit operation.

same applies for the second if condition.





just to let you know, you can even construct your conditions like this if i'm not mistaken:
$print_again = (!$_POST['uname'] || strlen($_POST['fname']) < 2);

although i would feel more comfortable with a more specific empty() function
$print_again = (!empty($_POST['uname']) || strlen($_POST['fname']) < 2);

those two lines do the same as your if condition.
also, consider the [a href=\"http://www.php.net/operators.comparison#language.operators.comparison.ternary\" target=\"_blank\"]ternary operator[/a].

#3 chrisbcats

chrisbcats
  • Members
  • PipPip
  • Member
  • 11 posts

Posted 06 June 2006 - 11:18 PM

Thanks! I fixed that '|' issue, and the problem I had going on with using different variable names.

Regarding the if statement is fixed it using:


if(isset($_POST["create"])) {
//code to check form
} else {
show_form();
}


I just put the form in a function, and that solved my issue




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users