Reputation: 3593
I'm using this piece of code to save an email into our database but if the user doesn't enter an email address then it inserts an empty row... what is the best way to stop this happening?
<?
if(isset($_POST['email'])) {
$email = $_POST['email'];
$email = mysql_real_escape_string($email);
$query = "INSERT INTO `email_capture` (`email_id`, `email_address`)
VALUES (NULL, '$email');";
mysql_query($query);
echo "";
mysql_close($email_sql);
}
else {
mysql_close($email_sql);
}
?>
Upvotes: 0
Views: 2906
Reputation: 1362
You should use empty()
to check the post
if (!empty($_POST['email'])) {
// ...
}
empty()
will check and return true if the variable is set and not empty. But it will also check for variables like 0
witch $_POST['email'] !== ''
will not.
Upvotes: 0
Reputation: 3874
Change your if
statement to:
if (!empty($_POST['email'])) {
// ...
}
No need to use isset()
when using empty()
.
Read more: http://php.net/manual/en/function.empty.php
Upvotes: 1
Reputation: 1085
Most simple way of doing this is to modify your html
code just add required attribute to your html
. Thats it now form won't be submitted unless users types email.
<input type="email" name="email" required="required" placeholder="Email"/>
Upvotes: -1
Reputation: 1521
Just don't only check if $_POST['email']
is set, but also check for an empty string:
if(isset($_POST['email']) && $_POST['email']!=""){
//your stuff here
}
Upvotes: 1