2015-10-28 89 views
-1

我正在使用以下代碼將電子郵件地址添加到數據庫中,如果電子郵件地址已經在數據庫中,我該如何忽略該過程?檢查電子郵件是否已在數據庫中

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); 
} 
+0

彌補這方面的電子郵件選擇查詢。如果您返回的ID表示電子郵件已經在數據庫中。 –

+0

http://stackoverflow.com/questions/22045788/check-if-email-exists-in-mysql-database – mohan111

+0

請停止使用'mysql_'函數並使用'mysqli_'或'PDO'來代替。 'mysql_'函數已經被棄用,並且將在今年晚些時候即將推出的PHP7版本中完全刪除。另請參閱[爲什麼不應該在PHP中使用mysql_ *函數?](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) – Oldskool

回答

0

如果您想避免更新電子郵件,也可以使用此rute。

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

另外請不要使用mysql擴展。查看mysqli或PDO

1

您可以在插入數據庫之前檢查數據庫中的那個電子郵件,如果電子郵件已經在數據庫中,請不要使用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); 
    } 
} 
+0

混合MySQL API –

+0

Fred-ii,對不起,但我不明白你想說什麼 – AkshayP

+0

'mysqli_num_rows'和'mysql_'不混爲一談。它必須完全一樣。 –

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); 
} 
相關問題