-1

I am using the following code to add an email address into a databse, how do I ignor the process if the email address is already in the database?

if(!empty($_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);

    mysql_close($email_sql);
}
Oldskool
  • 34,211
  • 7
  • 53
  • 66
Brad Fletcher
  • 3,547
  • 3
  • 27
  • 42
  • Make a select query for this email. If you get id returned that means email is already in database. – Rafał Cz. Oct 28 '15 at 12:33
  • http://stackoverflow.com/questions/22045788/check-if-email-exists-in-mysql-database – mohan111 Oct 28 '15 at 12:33
  • Please stop using `mysql_` functions and use `mysqli_` or `PDO` instead. The `mysql_` functions have been long deprecated and will be removed entirely in the upcoming PHP7 release later this year. Also see [Why shouldn't I use mysql_* functions in PHP?](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) – Oldskool Oct 28 '15 at 12:38

3 Answers3

1

You can check before inserting in DB where that email in there in DB, if email is already in DB don't use insert query.

if(!empty($_POST['email'])) {

    $email = $_POST['email'];

    //$email = mysql_real_escape_string($email);
    $email = trim($email);

    $query = "SELECT * from `email_capture` where `email_address` = '$email';";
    $result= mysql_query($query);

    $rowcount=mysql_num_rows($result);
    if($rowcount <=0) //if $rowcount is equal to zero means email is already in DB
    {
        $query = "
        INSERT INTO `email_capture` (`email_id`, `email_address`)
        VALUES (NULL, '$email');";

        mysql_query($query);
    }
}
AkshayP
  • 2,141
  • 2
  • 18
  • 27
0

You can also take this rute if you want to avoid updating an email.

INSERT INTO <table> (field1, field2, field3, ...) 
VALUES ('value1', 'value2','value3', ...)
ON DUPLICATE KEY UPDATE
field1='value1', field2='value2', field3='value3', ...

Also please don't use the mysql extention. Look into mysqli or PDO

Lohardt
  • 1,057
  • 1
  • 12
  • 26
0
 $sql_q="SELECT * FROM `email_capture` WHERE `email_address`='".$email."'";

//----then check the number of row return in zero or not.

$result=mysql_query($sql_q);
$num_rows = mysql_num_rows($result);

if($num_rows==0){

$email = $_POST['email'];

 $email = mysql_real_escape_string($email);

      $query = "INSERT INTO `email_capture` (`email_id`, `email_address`)VALUES (NULL, '$email')";
mysql_query($query);
mysql_close($email_sql);
}