-1

I have found out how to fetch for a username, however how would I do this with an email? Because, I want to add two separate error messages for an email and a username

$sql = "SELECT uid_users FROM users WHERE uid_users=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../register.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);

if ($resultCheck > 0) {
  header("Location: ../register.php?error=usertaken&mail=".$email);
  exit();
}
sahil
  • 27
  • 8

3 Answers3

3

Use OR to check another column.

$sql = "SELECT uid_users FROM users WHERE uid_users=? OR email = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
    header("Location: ../register.php?error=sqlerror");
    exit();
}
else {
    mysqli_stmt_bind_param($stmt, "ss", $username, $email);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);
    $resultCheck = mysqli_stmt_num_rows($stmt);

    if ($resultCheck > 0) {
        header("Location: ../register.php?error=usertaken&mail=".$email);
        exit();
    }
}

Note that this won't tell them whether it was the username or email that was already taken. If you want that, you should just do two separate queries, one that looks for a duplicate username, another that looks for a duplicate email.

Or you could change the query to SELECT uid_users, email and fetch the results of the query. Then check whether the fetched username or email matches the input, and display an appropriate error.

Barmar
  • 741,623
  • 53
  • 500
  • 612
2

You can use the OR operator for this:

   SELECT uid_users 
      FROM users 
     WHERE uid_users=? 
        OR email=?";```
Strawberry
  • 33,750
  • 13
  • 40
  • 57
Dimich
  • 359
  • 1
  • 9
0

If you want to check if a record exists in the database that matches both username and email then you should use WHERE uid_users=? AND email=?.

If you want to check if a a record exists in the database that matches either username or email, then use WHERE uid_users=? OR email=?.

Small note, you don't need to fetch the data if you only want to check existence of the record in DB. Simply let MySQL tell you the number of matching record. Use COUNT() for this purpose.

$stmt = $conn->prepare("SELECT COUNT(1) FROM users WHERE uid_users=? OR email=?");
$stmt->bind_param('ss', $username, $email);
$stmt->execute();
// Fetch value of COUNT(1) from DB
$resultCheck = $stmt->get_result()->fetch_row()[0];

if ($resultCheck) {
    header("Location: ../register.php?".http_build_query(['error' => 'usertaken', 'mail' => $email]));
    exit();
}
Dharman
  • 30,962
  • 25
  • 85
  • 135