2015-04-05 104 views
0

我對PHP相當陌生,一直遵循Lynda.com教程(儘管它們仍然使用mysql代替mysqli或PDO)。無法從PDO數組獲得價值

我在使用從我的查詢中獲得的數據時遇到問題。

我會用我的登錄頁面爲例,留出連接到數據庫部分:

$login_username = trim(htmlspecialchars($_POST['username'])); 
$password = trim(htmlspecialchars($_POST['password'])); // from login form 

$stmt = $db->prepare("SELECT * FROM users 
        WHERE username = :login_username"); 

$stmt->bindParam(':login_username', $login_username); 
$stmt->execute(); 
$result = $stmt->fetch(PDO::FETCH_ASSOC); 
if($stmt->rowCount() > 0 && $result = password_verify($password,$result['hashed_password'])) { 
$_SESSION['logged_in_id'] = $result['id']; 
$_SESSION['logged_in_username'] = $login_username; //this was the only way I could pass the username as I could not get it from $result['username'] 
$_SESSION['first_name'] = $result['first_name']; 
$_SESSION['last_name'] = $result['last_name']; 

沒有被傳遞到了會議,並沒有錯誤。我也不能回顯$ result的值。如果我只是嘗試echo $ result,那麼我只能得到1

請幫忙!

回答

1

您的問題是:

... && $result = password_verify($password,$result['hashed_password']) 

注意$result是包含行的一個數組,你只是牽強,你在這裏分配給它一個新的價值;您正在覆蓋您的變量$result,因此之後的所有分配都將失敗。

你可能想是這樣的:

... && password_verify($password,$result['hashed_password']) 

還要注意的是,你不應該依賴於rowCount()的不一定是你所期望的SELECT聲明。

因爲你已經取一排,你可以簡單地做:

if ($result && password_verify($password,$result['hashed_password'])) 

如果沒有結果,第二個條件將永遠不會被檢查,所以它不會導致警告或錯誤。

+1

你是我的英雄!非常感謝你,有道理,現在有用。 – 2015-04-05 18:14:37

+0

@FrancoisStander訪問http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work然後返回到答案,並執行相同的操作,以正確地關閉問題並將其標記爲解決了。 ;-) *歡迎使用Stack *。 – 2015-04-05 18:21:15

+0

明白了,謝謝。我愛這個網站:) – 2015-04-05 19:14:55