简体   繁体   English

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

[英]Query mySQL to check if user already exists in two tables

I am following a tutorial on how to create a user registration system for a website.我正在关注如何为网站创建用户注册系统的教程。 I've made it to this step but I need to check multiple values in two tables to see if they exist.我已经完成了这一步,但我需要检查两个表中的多个值以查看它们是否存在。 The tutorial doesn't do this.本教程不这样做。

Here is my registration form:这是我的注册表:

<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>

The mySQL database tables I need to check against are:我需要检查的 mySQL 数据库表是:

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

registered
  -id
  -nameFirst
  -nameLast
  -email
  -dob

I need to create a query that checks if ANY of the following already exist: 1) first AND last name together, 2) username, or 3) email.我需要创建一个查询来检查以下是否已经存在:1)名字和姓氏在一起,2)用户名,或 3)email。

Furthermore, once I understand how to perform a query like this, I am still a little confused as to what the ?此外,一旦我了解了如何执行这样的查询,我仍然对? is in the query.在查询中。 Also, this code example only checks if the username exists and outputs 'Username already exists.此外,此代码示例仅检查用户名是否存在并输出“用户名已存在”。 Please choose another.'请选择另一个。 I need to output different things based on which fields already exist in the table(s).我需要根据表中已经存在的字段来 output 不同的东西。 Here is the code from the tutorial:这是教程中的代码:

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();

Would it be like this?会是这样吗?

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

And again, I am learning how to do this using the tutorial so I don't want to change anything to the code in terms of how it operates.再一次,我正在学习如何使用教程来做到这一点,所以我不想就代码的操作方式对代码进行任何更改。 I understand that there are much better ways of doing this.我知道有更好的方法可以做到这一点。 I am using this as a starting point to learn and progress from.我以此为起点来学习和进步。

Since all you want to do is check whether the registration values already exist, it is probably easiest to use EXISTS subqueries rather than JOIN ing both tables together.由于您要做的就是检查注册值是否已经存在,因此使用EXISTS子查询而不是JOIN将两个表放在一起可能是最简单的。 Something like this:像这样的东西:

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

In this query the ?在这个查询中? represent placeholders for the username, first name, last name and email values.代表用户名、名字、姓氏和 email 值的占位符。 The purpose of using prepared statements with placeholders is to protect against SQL injection, for more information on that see this Q&A .使用带有占位符的准备好的语句的目的是防止 SQL 注入,有关更多信息,请参阅此 Q&A Using them also has the benefit of removing the need to escape special character in inputs (for example, if you wanted to insert O'Hara into the nameLast field using a value enclosed in single quotes).使用它们还有一个好处是无需转义输入中的特殊字符(例如,如果您想使用单引号括起来的值将O'Hara插入到 nameLast 字段中)。

So, for your code, you would do something like:因此,对于您的代码,您可以执行以下操作:

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();

I think you'll want your SQL statement to use a JOIN like this, to avoid duplicate row matching:我想你会希望你的 SQL 语句使用这样的JOIN ,以避免重复的行匹配:

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

Then you'll need to add the additional parameters to your bind:然后,您需要将附加参数添加到绑定中:

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

the?这? Is going to change.将要改变。 Keep in mind i Will avoid problems whit the double and triple comilla记住我会避免双重和三重comilla的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM