简体   繁体   中英

php check if email exists in mysql database

For some reason it always returns 0 even when there is an identical email in the database. Is there something wrong with my syntax? The code worked when I did it without a prepare/execute statement. Is it necessary here for security reasons?

$email= $conn->real_escape_string($_POST['email']);

function emailExists($conn, $email) {
    $stmt = $conn->prepare("SELECT 1 FROM accountInfo WHERE email=(?)");
    $stmt->bind_param($email);
    $stmt->execute();
    return $stmt->num_rows;
}

echo emailExists($conn, $email);

Don't use real_escape_string() . When you use parameter binding there is no need to escape anything.

Parameter binding in mysqli is rather difficult as you have to remember the strange syntax of bind_param() . At least 2 arguments are needed, the first is a string of characters representing the types of values. You don't have that.

SQL doesn't need brackets around parameters. You can just do email=? .

When you want to check the existence of something using SQL, then you don't need to use $stmt->num_rows . You can use COUNT(1) in SQL, which should be simpler. In fact, forget about the existence of this function/property as it leads to many mistakes like yours and is generally not useful.

When we fix all the small problems the code should look something like this:

$email = $_POST['email'];

function emailExists(mysqli $conn, string $email):bool {
    $stmt = $conn->prepare("SELECT COUNT(1) FROM accountInfo WHERE email=? LIMIT 1");
    $stmt->bind_param('s', $email);
    $stmt->execute();
    return (bool) $stmt->get_result()->fetch_row[0];
}

echo emailExists($conn, $email);

You just need to add $stmt->store_result();

function emailExists($conn, $email) {
    $stmt = $conn->prepare("SELECT 1 FROM accountInfo WHERE email=? LIMIT 1");
    $stmt->bind_param('s', $email);
    $stmt->execute();
    $stmt->store_result();
    return $stmt->num_rows;
}

Check this PHP code here

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