2017-05-09 83 views
0

即使輸入的id未被識別,$stmt->execute仍然返回true,因此程序不會輸出「錯誤的ID或密碼!」。我究竟做錯了什麼?

$id = $_POST["id"]; 
$pwd = $_POST["pwd"]; 

include("./sql/connect.php"); 

$stmt = $db->prepare("SELECT * FROM list WHERE id = :id AND pwd = :pwd"); 

$stmt->bindValue(":id", $id); 
$stmt->bindValue(":pwd", $pwd); 

if($stmt->execute()){ 
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)){ 
     echo $row["name"]; 
    } 
}else{ 
    echo "Wrong ID or Password!"; 
} 
+0

爲什麼它應該__not__返回true? –

+1

**永不**存儲純文本密碼。你應該使用['password_hash()'](http://us3.php.net/manual/en/function.password-hash.php)和['password_verify()'](http://us3.php。 net/manual/en/function.password-verify.php)。如果您使用的是5.5之前的PHP版本,請不要**使用MD5或SHA1來散列密碼。相反,您可以使用[此兼容包](https://github.com/ircmaxell/password_compat)。 –

+0

這裏沒有'return' - 只有'echo',你想檢查是否沒有行可能返回? –

回答

-1

你的查詢不會失敗它返回0個結果,所以$stmt->execute()將在這種情況下返回true。一個簡單的解決方法是將您的結果傳遞給數組,並檢查它是否爲空。 檢查出Example #2 Counting rows returned by a SELECT statementPDOStatement::rowCount它解釋了爲什麼你不應該使用rowCount爲SELECT和一個簡單的方法來做同樣的事情,但通過使用第二個查詢計數返回的行首先。我個人不會使用第二個查詢,所以這裏是編輯的例子。

if($stmt->execute()) { 
    $out = []; 
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
     $out[] = $row["name"]; 
    } 
    if(empty($out)) { 
     echo "no matching user is found"; 
    } else { 
     // rest of your code 
    } 
} else { 
    return $db->errorInfo(); 
} 

PS:我不得不感謝這位低調的選民。謝謝,答案確實需要編輯。

相關問題