2017-03-09 28 views
0

您好Stackoverflow社區,在PHP和PDO中創建一個例外以防止重複

我開始與PDO很快合作。我有一個微不足道的問題,我不知道如何解決。所以,讓我知道你們是否可以幫助我。

  1. 我有一個表單,旨在更新成員空間中用戶帳戶的數據。該表格有三個字段「姓氏」,「姓名」和「電子郵件」。

  2. 我不希望用戶註冊和現有的電子郵件。但是,如果用戶不想更新其電子郵件並且只想更改「姓氏」和「名稱」字段,則PHP代碼必須允許更新數據庫中的記錄。

  3. 我創建了一個函數來處理表單。它能夠防止重複記錄的插入,但它有一個問題。如果用戶不想更新他們的電子郵件,該函數返回數據庫中已經有相同的電子郵件。事實上,電子郵件已經存在,所以我想知道如何在我的代碼中實現此異常,以便在用戶不想更改電子郵件時更新記錄?

下面的功能:

function update_admin_profile() { 
    session_start(); 
    if (isset($_SESSION['id']) AND isset($_SESSION['login'])) { 
     // get the session variables for another propouse. 
     $id = $_SESSION['id']; 
     $pseudo = $_SESSION['login']; 

     // p - It's the URL parameter. anti_sql_injection is a function to check the parameter. 
     $p = anti_sql_injection($_GET['p']); 

     if (isset($_POST['last_name']) AND isset($_POST['name']) AND isset($_POST['email'])) { 
       $bdd = connexion_bdd(); 
       $query = $bdd->prepare('SELECT * FROM tbl__administrators WHERE email = :email'); 
       $query->execute(array('email' => htmlspecialchars($_POST['email']))); 
       $count=$query->rowCount(); 
       if ($count == 0) { 
        $update = $bdd->prepare('UPDATE tbl__administrators SET last_name = :last_name, name = :name, email = :email WHERE id = ' . $p); 
        $update->execute(array(
         'last_name' => htmlspecialchars($_POST['last_name']), 
         'name' => htmlspecialchars($_POST['name']), 
         'email' => htmlspecialchars($_POST['email']) 
         )); 
         //The profile was updated. 
         header('Location: notify.php?m=49'); 
       } else { 
        //The e-mail already exists! 
        header('Location: notify.php?m=48'); 
       } 
     } else { 
      //Please fill in all fields 
      header('Location: notify.php?m=41'); 
     } 
    } else { 
     //You session is expired. You will be disconnected now. Please, perform the login again and repeat this operation. 
     header('Location: notify.php?m=7'); 
    } 
} 

注:這是如果我改變了電子郵件功能的工作原理。

非常感謝您的幫助。

祝您有美好的一天。

回答

0

如果用戶不想更新他們的電子郵件,該函數返回數據庫中已經有相同的電子郵件。

這很簡單。只需添加另一個條件從查詢結果中排除當前用戶

$query = $bdd->prepare('SELECT 1 FROM tbl__administrators WHERE email = ? and id != ?'); 
$query->execute(array($_POST['email'], $id)); 
+0

非常感謝您的幫助。這很簡單。 – lfgoulart