-1

Possible Duplicate:
insert contacts into database but does not want to duplicate already existing contact

Hello. I'm trying to check if an email already exists before I insert a duplicate.

So I need to check the database for the presence of the email address and if it exists ouput a message saying it already exists. Otherwise I want to insert the record into the database.

Here is the code I use to insert the email now, but I'm not sure how to check the database for existence.

$addEmailQuery  = sprintf("INSERT INTO `subscribe`(`Email`) VALUES('%s')",
                            mysql_real_escape_string($_POST['inputEmail']));
        $addEmailResult = mysql_query($addEmailQuery);
        if($addEmailResult){
            echo 'Email successfully submitted';

        } else{
            echo 'Sorry, we could not submit your email. Please try again.';
        }

Anyone know how I would do this?

Community
  • 1
  • 1
user921334
  • 37
  • 3
  • 8

2 Answers2

0

Do a SELECT before your Insert and check if a value is returned for this email. Thats the simplest way to do it.

$CheckEmailQuery  = sprintf("SELECT `Email` FROM `subscribe` WHERE `Email` = '%s'",
                        mysql_real_escape_string($_POST['inputEmail']));
    $CheckEmailResult = mysql_query($CheckEmailQuery);
    if($CheckEmailResult){
        // Do What you are doing above
    }

I have just given the idea but not tested it.

Farrukh Subhani
  • 2,018
  • 1
  • 17
  • 25
-1

EDITED: The initial answer will pose problems in a multi-user environment.

You should do like

INSERT ... ON DUPLICATE KEY UPDATE

Follow this answer to get it correct.

ORIGINAL POST:

if(mysql_num_rows(mysql_query("SELECT * FROM subscribe WHERE Email = '".mysql_real_escape_string($_POST['inputEmail'])."'")))
{
     echo "already submitted";
}   
else
{

    $addEmailQuery  = sprintf("INSERT INTO `subscribe`(`Email`) VALUES('%s')",
                        mysql_real_escape_string($_POST['inputEmail']));
    $addEmailResult = mysql_query($addEmailQuery);
    if($addEmailResult)
    {
       echo 'Email successfully submitted';

     } 
     else
     {
        echo 'Sorry, we could not submit your email. Please try again.';
     }

}
Community
  • 1
  • 1
Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101