0
function SQL_QUERY_LOGIN_BY_SCHOOLCODE($con, $username, $opt=""){
    if(is_resource($con)){
        $q = "SELECT * FROM users WHERE username = '$username";
        $result = mysql_query($q);
        $row = mysql_fetch_array($result);
        $count = mysql_num_rows($result);
        if($count == 0) return  $opt="0";
        if($count > 1) return $opt="1";
    }
}

$mysql_login_result = SQL_QUERY_LOGIN_BY_USERNAME(MYSQL_LINK, $form_username, 1);

if($mysql_login_result == 0){
    $message = "User not registered, please register!";
}else{
    $message = "Success!";
}

Guys I have the code above to check whether the username exist or not, but when I enter the username that exist in the users table, it still echo user not registered message, what is wrong with my code?

  • 2
    You are **wide open** to SQL injection attacks, and you will be hacked if you haven't been already. Please use prepared / parameterized queries to prevent this from happening. See also: [How can I prevent SQL injection in PHP?](http://stackoverflow.com/questions/60174/) – Amal Murali Feb 16 '14 at 04:28
  • 3
    You are missing your closing single quote around your `$username` -> `'$username` -> `$q = "SELECT * FROM users WHERE username = '$username";` -- also sanitize your data to prevent injection – Sean Feb 16 '14 at 04:29
  • where's the function your using? it's not the one in the code you posted... posted function is BY_SCHOOLCODE you're calling BY_USERNAME – Bryan Feb 16 '14 at 05:45

1 Answers1

0

This part

if($count == 0) return  $opt="0";
if($count > 1) return $opt="1";

You should check if count is > 0 not one, because there will only be 1 row with a username, not > 1 rows;

if($count == 0) return  $opt="0";
if($count > 0) return $opt="1";

There is also no need to use a variable $opt, nor to use a string as return, just return an integer

if($count == 0) return 0;
if($count > 1) return 1;

Or a simple one liner:

return ($count > 1) 1 : 0;

And do look at the comments on SQL injection and so on.

Joshua Kissoon
  • 3,269
  • 6
  • 32
  • 58