2011-08-16 57 views
1

我是PDO PHP的新手(剛開始今天)。我試圖寫一個登錄函數,但它返回false,即使我知道憑據是正確的。PDO腳本獲取行數不工作?

我認爲是嘗試獲取觸發腳本的行數量,你能幫忙嗎?

function check_login($email, $username, $password) 
{ 
    $host = 'localhost'; 
    $port = 3306; 
    $database = 'example'; 
    $username = 'root'; 
    $password = ''; 

    $dsn = "mysql:host=$host;port=$port;dbname=$database"; 
    $db = new PDO($dsn, $username, $password); 
    $password = md5($password); 

    $statement = $db->prepare("SELECT * FROM users WHERE email = ? or username = ? and password = ?"); 
    $statement->execute(array($email, $username, $password)); 

    while ($result = $statement->fetchObject()) { 
     $sql = "SELECT count(*) FROM users WHERE email = ? or username = ? and password = ?"; 
     $result1 = $db->prepare($sql); 
     $result1->execute(array($email, $username, $password)); 
     $number_of_rows = $result1->fetchColumn(); 
     if ($number_of_rows == 1) 
     { 

      $_SESSION['login'] = true; 
      $_SESSION['uid'] = $result->uid; 
      return TRUE; 
     } 
     else 
     { 
      return FALSE; 
     } 
    } 
} 

回答

1
  1. 此:

    WHERE email = ? or username = ? and password = ? 
    

    ...等於此:

    WHERE email = ? or (username = ? and password = ?) 
    

    ...由於operator precedence。這意味着如果您使用電子郵件地址進行驗證,則不需要提供有效的密碼來登錄。

  2. 一旦找出用戶是否存在,您將進行第二次查詢以計算匹配用戶的數量。數據庫表不應該能夠容納重複的用戶!應該將列usernameemail定義爲唯一索引。

  3. 如果要在第一次迭代中使用return,則使用while循環沒有意義。它可能工作,但它很混亂。

這應該是足夠了:

$statement = $db->prepare('SELECT uid FROM users WHERE (email = ? or username = ?) and password = ?'); 
$statement->execute(array($email, $username, $password)); 

if ($result = $statement->fetchObject()) { 
    $_SESSION['login'] = true; 
    $_SESSION['uid'] = $result->uid; 
    return TRUE; 
}else{ 
    return FALSE; 
} 

編輯: BTW,你不應該採用明文存儲密碼。無數的網站被黑客入侵,密碼被盜。 Google爲醃製密碼