A problem with my code for a simple $_POST form

I’m trying to have a simple form with ‘email’ and ‘password’ to be posted into my DB. Here is my code so far:

if (array_key_exists('email',$_POST) || array_key_exists('password', $_POST)){
        
        $link = mysqli_connect("localhost", "root", "", "users");
    
        if (mysqli_connect_error()) {
            die ("Connection has failed");   
        };
        
        $query = "SELECT `email` FROM users WHERE email = '".mysqli_real_escape_string($link, $_POST['email'])."'";
        
        
        if (mysqli_query($link, $query)) {
                
            echo "<p>Email address is already registered!!</p>";
            
        } else {
            
            $query = "INSERT INTO `users` (`email`,`password`) VALUES ('".mysqli_real_escape_string($link, $_POST['email'])."', '".mysqli_real_escape_string($link, $_POST['password'])."')";
            
            mysqli_query($link, $query);
            
            echo "Congrats! You are now signed-up!";
            
        };
        
    };

I believe that there is something wring with this statement:

if (mysqli_query($link, $query)) {
                
            echo "<p>Email address is already registered!!</p>"

Because no matter what my entry is, it always returns “Email address is already registered!!”, but I just do not understand why it does not go to the “else” statement if the query is “false” !!

Can someone please explain !?

mysqli_query returns a result-object, but not the wanted result itself. You always have a result-object. You must check the “inner” of the result-object:
$result = mysqli_query(…)
if(mysqli_num_rows($result) > 0)…

here is a complete example:
http://php.net/manual/de/mysqli.query.php

Still, according to the documentation:

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE .

If it returns FALSE on failure, why it does not go all the way to the ELSE statement and still

echo "<p>Email address is already registered!!</p>";

If you query something and there is no result, then it is NOT a failure.
select email from… may return

  • 1 email
  • or 10 emails
  • or 0 email.
    All that is not a failure.

But if you select something impossible, e.g.:
select eemail from
it’s a failure cause eemail does not exist.

1 Like

Oh, ok…Now I get what you mean.

In that case, I guess your approach below would be a solution

Mine would never work in this case…

Thanks a lot for the explanation!!