Jump to content

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.
Link to comment
https://forums.phpfreaks.com/topic/11356-if-statements-and-variables/
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].
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
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.