Question

function IsEmailRegistered($Email){
    global $con;
    $result = mysqli_query($con,"SELECT email FROM Users WHERE email = '" . $Email . "'");
    if (mysqli_num_rows($result) > 0){
        return True;
    }else{
        return False;
    };
};

that's a function that checks if an email is registered before, the function returns 1 if the email is registered and returns nothing (instead of 0) if it's not registered. What I'm missing here?

Was it helpful?

Solution

If you get 1 and 0 as result, you are echoing it. Your code is probally right, you just misinterpreted it

echo true; // screen will say 1
echo false; // screen will say 0
var_dump($var); // this will give you the value (true) and its type (boolean)

This always returns true or false. Also added a limit to your query, you only need 1 hit to check it. If you need an exact amount of rows, specify it. E.g. when you want 1 row, use LIMIT 1. When your site grows, this will save precious resources.
Here you have your functions, optimised (IMO)

function IsEmailRegistered($Email){
    global $con;
    $result = mysqli_query($con,"SELECT email FROM Users WHERE email = '".$Email."' LIMIT 1");
    return mysqli_num_rows($result)===1; // this function will return true/false
}

If you want to stick with the if/else, you can use a ternary, the code below will do the exact same thing as your code does:

return mysqli_num_rows($result) > 0 ? true : false;

I changed the true/false to lowercase, always lowercase them for consistancy. You might encounter a situation where you have to send 'true' or 'false', you dont want to waste time on something that didnt work because you used a capital :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top