Jump to content

Archived

This topic is now archived and is closed to further replies.

chrisbcats

if statements and Variables

Recommended Posts

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


[code]
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');
}
}[/code]

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.

Share this post


Link to post
Share on other sites
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:
[code]
$print_again = (!$_POST['uname'] || strlen($_POST['fname']) < 2);
[/code]

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

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].

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.