2015-11-08 70 views
1

我正在使用社交網絡,如果用戶名或電子郵件地址相同,我不想將詳細信息輸入到MySQL數據庫中。如果不存在,請插入

下面是我使用的PHP:

if (isset($_POST['username']) && isset($_POST['password'])){ 

    $datejoined = date('m/d/Y h:i:s a', time());; 
    $verified = 0; 
    $username = $_POST['username']; 
    $email = $_POST['email']; 
    $password = $_POST['password']; 

    $query = "INSERT INTO `members` (username, password, email, verified, datejoined) 
     VALUES ('$username', md5('$password'), '$email', '0', '$datejoined')"; 

一些幫助真的可以理解!

+0

您需要使用'如果-else',何地需要。 –

+1

爲數據庫中的這些字段添加一個唯一約束? – TZHX

+0

請參閱http://stackoverflow.com/questions/8449540/php-detect-mysql-update-insertion-failure-due-to-violated-unique-constraint – wil93

回答

1

創建唯一索引以找出重複項。

create unique index unq_members on members(username); 
create unique index unq_members on members(email); 

然後,做一個插入時忽略重複:

INSERT IGNORE INTO `members`(username, password, email, verified, datejoined) 
    VALUES ('$username', md5('$password'), '$email', '0', '$datejoined'); 

或使用:

INSERT INTO `members`(username, password, email, verified, datejoined) 
    VALUES ('$username', md5('$password'), '$email', '0', '$datejoined') 
    ON DUPLICATE KEY UPDATE username = username; 
+1

**注意:**'IGNORE'部分忽略更多的東西,而不僅僅是重複插入。 [更多](http://stackoverflow.com/questions/548541/insert-ignore-vs-insert-on-duplicate-key-update)和[更多](https://dev.mysql.com/doc/refman /5.6/en/insert.html) – FirstOne