Search code examples
phpdatabaseemailmysqliconfirmation

Checking if email exists in MySQLi database using PHP


I'm trying, as many others here have before me, to check if an email already exists in my database during account registration on my website, using PHP to interact with a MySQLi database. I've tried using as many guides as I could find here but still no luck.

Below is the code I originally wrote to insert the email of users into my database upon registration:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $database = new mysqli("localhost", "user", "dbpw", "dbname");
if($database->connect_error){
            die( "Error connecting:" . $database->connect_error);
        }

$email = $database->real_escape_string(htmlspecialchars($_POST["email"]));
$query = "SELECT email FROM Users WHERE email =$email";
$result = $database->query($query);
$numOfRows = $database->num_rows($result);
if($numOfRows > 0){
  echo "Email already exists in our database.";
}else{
$query = "INSERT INTO Users (email) VALUES ('" . $email . "');
if(!$database->query($query)){echo("<p>Unable to add user for query: " . $query . " <br /> Error: " . $database->errno . " " . $database->error);}}

Prior to inserting the email check (the if($numOfRows) statement), my database was being updated properly.

However, after adding my attempted email check, the page completely broke. My database wouldn't update with unique passwords, and it wouldn't display the echoed message "Email already exists in our database" if the email was a duplicate. The page would load, but with just the basic header, footer, and background CSS I have linked to every page.


Solution

  • Instead of using

    $numOfRows = $database->num_rows($result);
    

    Use

    if($result ->num_rows)
    {
    }