【问题标题】:Create an exception in PHP and PDO to prevent duplicates在 PHP 和 PDO 中创建异常以防止重复
【发布时间】:2017-07-30 06:48:36
【问题描述】:

你好 Stackoverflow 社区,

我很快就会开始使用 PDO。我有一个琐碎的问题,我不知道如何解决。所以,如果你们能帮助我,请告诉我。

  1. 我有一个表单,旨在更新成员空间中用户帐户的数据。此表单包含三个字段“姓氏”、“姓名”和“电子邮件”。

  2. 我不希望用户注册和现有的电子邮件。但是,如果用户不想更新他们的电子邮件而只想更改“姓氏”和“姓名”字段,则 PHP 代码必须允许更新数据库中的记录。

  3. 我创建了一个函数来处理表单。它能够防止重复记录的插入,但它有一个问题。如果用户不想更新他们的电子邮件,该函数会返回数据库中已经存在相同的电子邮件。其实email已经存在了,所以我想知道如何在我的代码中实现这个异常,让它在用户不想更改他们的email时更新记录?

函数下方:

    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');
    }
}

注意:如果我更改电子邮件,它的功能会起作用。

非常感谢您的帮助。

祝你有美好的一天。

【问题讨论】:

    标签: php mysql pdo duplicates


    【解决方案1】:

    如果用户不想更新他们的电子邮件,该函数会返回数据库中已经存在相同的电子邮件。

    这很简单。只需添加另一个条件即可将当前用户从查询结果中排除

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

    【讨论】:

    • 非常感谢您的帮助。真的很简单。
    猜你喜欢
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 2019-02-15
    • 2014-01-07
    • 2017-06-03
    • 1970-01-01
    相关资源
    最近更新 更多