php - 在 PHP 和 PDO 中创建异常以防止重复

标签 php mysql pdo duplicates

Stackoverflow 社区您好,

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

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

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

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

非常感谢您的帮助。

祝你有美好的一天。

最佳答案

If the user does not want to update their email, the function returns that there is already an equal email in the database.

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

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

关于php - 在 PHP 和 PDO 中创建异常以防止重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42692727/

相关文章:

php - HipHop PHP 编译器的 C++ 输出是什么样的?

php - 数组到字符串转换注意事项。为什么?

php - 在 VideoJS 脚本上禁用视频下载

java - Tomcat 日历 Web 应用程序 mysql : MySQLNonTransientConnectionException:

PHP更新大型数据库

php - 将数据库条目与表单进行比较

mysql - 无法在mysql表上创建外键

mysql - Laravel 数据库查询 now()

mysql - Pdo更新函数

php - 尝试使用 jquery .load 根据表单中的特定输入将 PHP mysql 行打印到 div 中