Need_Help
Need_Help

Reputation: 11

My condition is not working(prepared query and POST method + isset function)

I'd like to verify if an user entered something in an input tag :

here is the index.php page :

<form action="email_validation.php" method="post">
    <p>
     Enter email :  <input type="text" name="email" id="email" /><br />
    <input type="submit" value="Envoyer" />
</p>
</form>

and the email_validation.php :

 if(isset($_POST['email']))
 {
    $req = $bdd->prepare('INSERT INTO newsletter(email) VALUES(:email)');
    $req->execute(array(
    'email' => $entree = $_POST['email']
));

echo 'Email added';
}
else
{
    echo 'Enter something';
}

It seems that my condition with isset() function is not working... when I'm testing this, "Email added" is displayed even if I'm not writing anything and a blank value is added to the database . When someone write nothing, I want to display "Enter something" and don't execute the query. I searched for hours and can't resolve this... Thanks is advance !

Upvotes: 0

Views: 85

Answers (2)

Alex
Alex

Reputation: 810

You are not validating the input. You are just testing if the value exists. And it is, the _POST will have the email field, with an empty value. In order to validate it, the code should be:

if(!empty($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    $req....
} else {
    echo "No valid email provided";
}

Hope that helps.

Upvotes: 1

Elon Than
Elon Than

Reputation: 9765

That's because isset will check if variable is set and is not null.

When you send your form without typing email $_POST['email'] will contain empty string so isset will return true.

You have to use empty for that (or check length) and also it's good idea to additionally check if email is in correct format.

Upvotes: 0

Related Questions