pp182
pp182

Reputation: 107

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);

Upvotes: 0

Views: 829

Answers (2)

Slava Rozhnev
Slava Rozhnev

Reputation: 10163

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

Upvotes: 2

Dharman
Dharman

Reputation: 33238

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);

Upvotes: 2

Related Questions