检查多个值是否重复

bkkx9g8r  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(220)

我有下面的代码来检查 username 已经用过了,我还需要用4个字段。

if ($valid) {
    $pdo = Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql2 = "SELECT * FROM users WHERE username = ?";
    $q2 = $pdo->prepare($sql2);
    $q2->execute(array($username));
    $result = $q2->fetchAll();

    if (count($result) > 0) {
        $usernameError = 'O utilizador já existe!';
    } 
    else{
        $sql = "INSERT INTO users (username,password,role) values(?, ?, ?)";
        $q = $pdo->prepare($sql); 
        $q->execute(array($username,$password,$role)); 
        header("Location: index.php");
    }

    Database::disconnect();
}
q3qa4bjr

q3qa4bjr1#

如果您需要知道哪些字段已经复制,请使用以下方法:

SELECT MAX(username = :username) AS usernameError, MAX(email = :email) AS emailError, MAX(phone = :phone) AS phoneError
FROM users
WHERE username = :username OR email = :email or phone = :phone

然后可以为结果中等于的每列生成相应的错误消息 1 .

相关问题