简体   繁体   中英

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.

Instead of using

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

Use

if($result ->num_rows)
{
}

You need to add single quotation marks around the email variable. Like this '$email'. Check the below code.

$query = "SELECT email FROM Users WHERE email = '$email'";

And you need to edit your conditional statement to check whether its greater than or equal to 0 or you can just use variable as boolean in condition block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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