且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查MySQL中是否存在行? (即检查MySQL中是否存在电子邮件)

更新时间:2023-11-25 21:29:58

以下经过尝试,测试和验证的方法来检查是否存在行.

The following are tried, tested and proven methods to check if a row exists.

(其中一些我自己使用过,或者曾经使用过).

(Some of which I use myself, or have used in the past).

编辑:我在语法上犯了一个先前的错误,我两次使用mysqli_query().请查阅修订版本.

I made an previous error in my syntax where I used mysqli_query() twice. Please consult the revision(s).

即:

if (!mysqli_query($con,$query)),应该简单地读为if (!$query).

  • 我很抱歉忽略了这个错误.

旁注: '".$var."''$var'都做相同的事情.您可以使用任何一种,两者都是有效的语法.

Side note: Both '".$var."' and '$var' do the same thing. You can use either one, both are valid syntax.

这是两个已编辑的查询:

Here are the two edited queries:

$query = mysqli_query($con, "SELECT * FROM emails WHERE email='".$email."'");

    if (!$query)
    {
        die('Error: ' . mysqli_error($con));
    }

if(mysqli_num_rows($query) > 0){

    echo "email already exists";

}else{

    // do something

}

以及您的情况:

$query = mysqli_query($dbl, "SELECT * FROM `tblUser` WHERE email='".$email."'");

    if (!$query)
    {
        die('Error: ' . mysqli_error($dbl));
    }

if(mysqli_num_rows($query) > 0){

    echo "email already exists";

}else{

    // do something

}

您还可以将 mysqli_与预准备的语句一起使用方法:

You can also use mysqli_ with a prepared statement method:

$query = "SELECT `email` FROM `tblUser` WHERE email=?";

if ($stmt = $dbl->prepare($query)){

        $stmt->bind_param("s", $email);

        if($stmt->execute()){
            $stmt->store_result();

            $email_check= "";         
            $stmt->bind_result($email_check);
            $stmt->fetch();

            if ($stmt->num_rows == 1){

            echo "That Email already exists.";
            exit;

            }
        }
    }

或带有准备好的语句的PDO方法 :

<?php
$email = $_POST['email'];

$mysql_hostname = 'xxx';
$mysql_username = 'xxx';
$mysql_password = 'xxx';
$mysql_dbname = 'xxx';

try {
$conn= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password); 
     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
     exit( $e->getMessage() );
}

// assuming a named submit button
if(isset($_POST['submit']))
    {

        try {
            $stmt = $conn->prepare('SELECT `email` FROM `tblUser` WHERE email = ?');
            $stmt->bindParam(1, $_POST['email']); 
            $stmt->execute();
            while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

            }
        }
        catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }

    if($stmt->rowCount() > 0){
        echo "The record exists!";
    } else {
        echo "The record is non-existant.";
    }


    }
?>