查询 mySQL 以检查用户是否已存在于两个表中

Query mySQL to check if user already exists in two tables

我正在学习有关如何为网站创建用户注册系统的教程。我已经做到了 step 但我需要检查两个 table 中的多个值以查看它们是否存在。本教程不会这样做。

这是我的注册表:

<form action="/members/register/" name="registerForm">
    <div>
        <h2>Register</h2>
        <h6>welcome</h6>
        <div class="register">
            <input type="text" name="firstname" placeholder="First Name" required>
            <input type="text" name="lastname" placeholder="Last Name" required>
            <input type="text" name="email" placeholder="Email" required>
            <label for="dob">Date of Birth:
                <input type="date" name="dob" id="dob" placeholder="Date of Birth" required>
            </label>
            <input type="text" name="username" placeholder="Username" required>
            <input type="password" name="password" placeholder="Password" required>
            <input type="password" name="passwordconfirm" placeholder="Confirm Password" required>
            <p>By creating an account you agree to our <a href="/legal/terms-of-use/">Terms &amp; Privacy</a>.</p>
            <button type="submit" name="registerNow">Register</button>
        </div>
    </div>
</form>

我需要检查的 mySQL 数据库 table 是:

users
  -id
  -username
  -password
  -userID (foreign key)

registered
  -id
  -nameFirst
  -nameLast
  -email
  -dob

我需要创建一个查询来检查以下任何一项是否已经存在:1) 名字和姓氏,2) 用户名​​,或 3) 电子邮件。

此外,一旦我理解了如何执行这样的查询,我仍然对查询中的 ? 是什么感到有点困惑。此外,此代码示例仅检查用户名是否存在并输出 'Username already exists. Please choose another.' 我需要根据 table(s) 中已存在的字段输出不同的内容。这是教程中的代码:

if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the account exists in the database.
if ($stmt->num_rows > 0) {
    // Username already exists
    echo 'Username already exists. Please choose another.';
} else {
    // Insert new account
}
$stmt->close();
} else {
// Something is wrong with the sql statement, check to make sure accounts table exists with all 3 fields.
echo 'Could not prepare statement!';
}
$con->close();

会不会是这样?

SELECT id, password 
FROM users, registered 
WHERE users.username = ? OR (registered.nameFirst = ? AND registered.nameLast = ?) OR registered.email = ?

再一次,我正在学习如何使用教程来执行此操作,因此我不想在代码的运行方式方面对其进行任何更改。我知道有更好的方法可以做到这一点。我以此为起点来学习和进步。

因为您要做的只是检查注册值是否已经存在,使用 EXISTS 子查询可能比 JOIN 将两个表放在一起更容易。像这样:

SELECT
    EXISTS (SELECT * FROM users WHERE username = ?) AS found_username,
    EXISTS (SELECT * FROM registered WHERE nameFirst = ? AND nameLast = ?) AS found_name,
    EXISTS (SELECT * FROM registered WHERE email = ?) AS found_email

在此查询中,? 表示用户名、名字、姓氏和电子邮件值的占位符。使用带占位符的准备语句的目的是防止 SQL 注入,有关更多信息,请参阅 this Q&A。使用它们还有一个好处,即无需在输入中转义特殊字符(例如,如果您想使用单引号括起的值将 O'Hara 插入到 nameLast 字段中)。

因此,对于您的代码,您可以执行以下操作:

if ($stmt = $con->prepare('SELECT
        EXISTS (SELECT * FROM users WHERE username = ?) AS found_username,
        EXISTS (SELECT * FROM registered WHERE nameFirst = ? AND nameLast = ?) AS found_name,
        EXISTS (SELECT * FROM registered WHERE email = ?) AS found_email')) {
    // Bind parameters (s = string, i = int, b = blob, etc)
    $stmt->bind_param('ssss', $_POST['username'], $_POST['firstname'], $_POST['lastname'], $_POST['email']);
    $stmt->execute();
    $stmt->bind_result($found_username, $found_name, $found_email);
    $stmt->fetch();
    // Store the result so we can check if the account exists in the database.
    if ($found_username) {
        // Username already exists
        echo 'Username already exists. Please choose another.';
    }
    elseif ($found_name) {
        // Name already exists
        echo 'Name already exists. Please choose another.';
    }
    elseif ($found_email) {
        // Email already exists
        echo 'Email already exists. Please choose another.';
    }
    else {
        // Insert new account
    }
    $stmt->close();
} 
else {
    // Something is wrong with the sql statement, check to make sure accounts table exists with all 3 fields.
    echo 'Could not prepare statement!';
}
$con->close();

我认为您会希望 SQL 语句像这样使用 JOIN,以避免重复的行匹配:

    SELECT 
      users.id, password 
    FROM 
      users JOIN registered 
    USING(id) 
    WHERE 
      username = ? 
      OR (nameFirst = ? AND nameLast = ?) 
      OR email = ?

然后您需要将额外的参数添加到您的绑定中:

$stmt->bind_param(
   'ssss', 
   $_POST["username"], 
   $_POST["firstname"], 
   $_POST["lastname"], 
   $_POST["email]
);
$stmt->execute();
// etc.