aborted
aborted

Reputation: 4541

MySQL not returning to my needs

I am trying to create a function that is going to check if an user exists based on their email. After comparing the submitted email with the email entries in my database, I want to see if an user is legit or not. This is what I have coded so far:

function user_exists($email)
{
    $email = mysql_real_escape_string($email);
    $query = mysql_query("SELECT COUNT(`id`) FROM `imgit_users` WHERE `email`='$email'");

    return (mysql_result($query, 0) <= 1) ? true : false;
}

And I used it like this:

if (user_exists($register_email) === true)
{
    echo 'Fail';
    $errors[] = 'The supplied email is already in use';
}   
else 
{
    if (empty($errors))
    {
        $user_id = user_register($register_username, $register_email, $register_password);
        $_SESSION['imgit_uid'] = $user_id;
        echo 'Okay';
    }
}

My script keeps returning Okay instead of Fail, even if I type in the same email everytime. Ideas?

Upvotes: 0

Views: 385

Answers (4)

wonk0
wonk0

Reputation: 13982

I would prefer not use COUNT() to check if an email is already used, instead I'd use something like

function user_exists($email)
{
 $sql = sprintf( 
  'SELECT 1 FROM imgit_users WHERE email = \'%s\' LIMIT 0,1', 
  mysql_real_escape_string( $email ) 
 );
 $result = mysql_query( $sql );
 // add error handling
 return 1 === mysql_num_rows( $result );
}

Upvotes: 1

Sandro
Sandro

Reputation: 3160

return (mysql_result($query, 0) >= 1) ? true : false;

Upvotes: 1

yokoloko
yokoloko

Reputation: 2860

return (mysql_result($query, 0) >= 1) ? true : false;

Swap the <= to >=

Upvotes: 2

&#211;lafur Waage
&#211;lafur Waage

Reputation: 70041

return (mysql_result($query, 0) <= 1) ? true : false;

So you want to return true if the result is less than or equal to 1. So if it's 1 or 0? Perhaps there is your error, to check if it is less than 1 and swap the true / false. Or check if it is equal to 1.

Upvotes: 2

Related Questions