简体   繁体   English

使用PHP检查MySQLi数据库中是否存在电子邮件

[英]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. 我正在尝试像在此之前的其他许多人一样,使用PHP与MySQLi数据库进行交互,以检查在我的网站上进行帐户注册期间数据库中是否已存在电子邮件。 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. 在插入电子邮件支票(if($ numOfRows)语句)之前,我的数据库已正确更新。

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. 该页面将被加载,但是只有基本的页眉,页脚和背景CSS我已链接到每个页面。

Instead of using 而不是使用

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

Use 采用

if($result ->num_rows)
{
}

You need to add single quotation marks around the email variable. 您需要在email变量周围添加单引号。 Like this '$email'. 像这样的“ $ 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. 并且您需要编辑条件语句以检查其是否大于或等于0,或者可以在条件块中仅将变量用作布尔值。

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

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