Brad Fletcher
Brad Fletcher

Reputation: 3593

Don't enter into database if field is empty

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

Answers (4)

Thaillie
Thaillie

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

John Dorean
John Dorean

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

bɪˈɡɪnə
bɪˈɡɪnə

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

nameless
nameless

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

Related Questions