Tommy Solheim
Tommy Solheim

Reputation: 21

PHP boolean error

Im a newbie to php trying understand why i get boolean error in my specific case with a code that works for others. I have a function that returns a $user_id which is to be used in a session later on. Here is he function:

    function login($username, $password) {
       $user_id = user_id_from_username($username);
       $username = sanitize($username);
       $password = sha1($password);
       return (mysql_result(mysql_query("SELECT COUNT (user_id) FROM users WHERE username = '$username' AND password = '$password'"), 0) == 1) ? $user_id : false ;
   } 

This always results in a fail, with this error: Warning: mysql_result() expects parameter 1 to be resource, boolean given in. with a line number that points to this line.

  return (mysql_result(mysql_query("SELECT COUNT (`user_id`) FROM users WHERE username      = '$username' AND password = '$password'"), 0) == 1) ? $user_id : false ;

Why does this fail ? Isn't this enough to check weather the query was successful and test result. DB connection and sql query seemed to be correct, doesn't matter whether i use ' or omit. After several hours of research i managed to remove the error with an if statement. Like so :

    function login($username, $password) {
       $user_id = user_id_from_username( $username );
       $username = sanitize( $username );
       $password = sha1( $password );
       $result = mysql_query("SELECT COUNT (user_id) FROM users WHERE username = '$username'AND password = '$password'");
       if ( $result == 1 ) {
           return $user_id;
       } else if ( $result == 0 ) {
           return false;
       }
   }

I would like to know why the second function works and not the first. Do you have to use an if statement to check the query ? If there is a better way to write this function please suggest.:)

Upvotes: 0

Views: 140

Answers (1)

Narek
Narek

Reputation: 3823

Probably you have error in query so mysql_query return false

Replace:

return (mysql_result(mysql_query("SELECT COUNT (user_id) FROM users WHERE username = '$username' AND password = '$password'"), 0) == 1) ? $user_id : false ;

with:

$result = mysql_query("SELECT COUNT(user_id) as count FROM users WHERE username = '$username' AND password = '$password'") or die(mysql_error());

return (mysql_result($result, 0, 'count') == 1) ? $user_id : false ;

and you will see mysql error.

Upvotes: 1

Related Questions