Search code examples
phphtmlmysqlemail-validation

PHP Checking if the email already exists in the database


I am making a website with a login system. When the user wants to sign up and enters his email, there should not exist one in the MySQL database already. I am trying to make my code through prepared statements.

When the user enters an email that already exists in the database I want it to send the user back to the same signup page with the header function with some kind of error. I tried to store the number of rows in a variable called $resultcheck and check whether or not there are columns that have the same email more than 0 (if it already exists).

Here is the code:

$query = "SELECT * FROM users WHERE Mail=?;";
        $stmt = mysqli_stmt_init($conn);
        if(!mysqli_stmt_prepare($stmt, $query))
        {
            header("Location: ../registrering.php?error=sqlerror");
            exit();
        }
        else
        {
            mysqli_stmt_bind_param($stmt, "s", $mail);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_store_result($stmt);
            $resultCheck = mysqli_stmt_num_rows($stmt);
            if($resultcheck > 0)
            {
                header("Location: ../registrering.php?error=emailtaken");
                exit();
            }
            else {...}

When I submitted however an account with an already existing email in the database then I succesfully entered another column in the table users and have more than one column with the same email.


Solution

  • You are assigning $resultCheck and then testing for another variable called $resultcheck which will always be 0.

    So your mistake is a typo in your variable naming.