2014-10-11 157 views
-3

我忙於一個PHP/MySQL登錄系統,只是爲了好玩。 我做了這樣的功能:PHP - MySQL爲什麼這個查詢永遠不會返回false?

function login($username, $password) { 
    $user_id = user_id_from_username($username); 
    $password = md5($password); 

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

但由於某些原因,它總是返回USER_ID,決不會爲假,即使登錄憑據是錯誤的!

+6

你爲什麼還在使用'mysql_'庫 - 它已過時 – 2014-10-11 09:58:54

+0

此外,'md5hash()'不應該與密碼一起使用... – arkascha 2014-10-11 09:59:55

+0

@EdHeal正如我所說的,我是爲了好玩,我不必保護它免受SQL注入,我不必使用最新的功能。這只是爲了好玩 – bramhaag 2014-10-11 10:00:42

回答

1
function login($username, $password) { 
    //$user_id = user_id_from_username($username); // remove this line down to the if statement 
    $password = md5($password); 

    $query = mysql_query("SELECT `username`, `password` FROM `users` WHERE `username` = '$username' AND `password` = '$password'"); 

    // Check if the query was a success 
    if($query) { 
     // Check if there is a user with the matching data 
     if(mysql_num_rows($query) > 0) { 
      $user_id = user_id_from_username($username); // To here. So now this is only called when the credentials are correct 
      return true; 
     } else { 
      return false;  
     } 
    } 
    } 

,但你真的應該開始期運用mysqli_*PDOmysql_*已被廢棄,因爲PHP7的去除。也不要相信md5(),因爲它很容易破解。使用類似hash('sha512', md5($password));

嘗試以下操作:

$result = mysql_query("SELECT `active` FROM `users` WHERE `username` = '$username'"); 
$return = mysql_result($result, 0); // Should be 0 or 1, I don't know this for sure. You need to try it out 

// If query is a success 
if($result) { 
    if ($return > 0 && $return < 3) { 
     return true 
    } else { 
     return false; 
    } 
} 
+0

謝謝,我現在會嘗試這個 – bramhaag 2014-10-11 10:07:09

+0

嗯...似乎沒有工作:( – bramhaag 2014-10-11 10:09:40

+0

@bramhaag哦,等等,我只是注意到你正在檢查'$ username',所以我會修復這個問題的答案。 – SuperDJ 2014-10-11 10:10:54

相關問題