2014-05-07 135 views
-2

當我使用下面的代碼時,我得到Undefined Index: email on $row['email']。如果我用$row和print_r獲取整個數組,它將顯示它應該顯示的樣子。 我哪裏錯了?fetchAll(PDO :: FETCH_ASSOC)不返回單個值

  $stmt = $db->dbh->prepare("SELECT email FROM $this->table WHERE `email`= :email"); 
      $stmt -> bindValue(':email', $email); 
      $stmt->execute(); 
      while ($row = $stmt->fetchAll()){ 
       return $row['email']; 
       } 

$new = new Users; 
echo $new->reset_password($email); 
} 
+0

'fetchAll' ...獲取所有,使用'fetch' – cmorrissey

+0

既然你的循環,你需要'而($行= $ stmt- > fetch()){'而不是'while while($ row = $ stmt-> fetchAll()){' – Sean

+2

爲什麼你選擇的是你已經知道的電子郵件? –

回答

2

fetchAll返回所有結果的二維數組。要一次只得到一行,您應該撥打$stmt->fetch(),而不是$stmt->fetchAll()

while ($row = $stmt->fetch()) { 
    ... 
} 

但是既然你回來了,你根本不應該使用循環。 return語句將在第一次迭代之後終止循環。只需使用if聲明。

if ($row = $stmt->fetch()) { 
    return $row['email']; 
} 

這整個代碼沒有多大意義 - $newemail保證是一樣$email,爲什麼要退呢?這也許應該是:

if ($stmt->fetch()) { // Email was found 
    return true; 
} else { 
    return false; 
} 
+0

謝謝。所做的是檢查是否找到,然後在郵件中使用電子郵件()。 – hello

+0

你不能使用你傳遞的原始變量作爲參數嗎? – Barmar

+0

在那裏我仍然需要檢查它是否存在於數據庫中,然後查看是否有任何行被返回,然後發送密碼重置代碼 – hello

0

您應使用此代碼:

while ($row = $stmt->fetch()){ 
    $newemail = $row['email'];    
} 

,而不是驗證碼:

while ($row = $stmt->fetchAll()){ 
    $newemail = $row['email']; 
} 

方法fetchAll()取在單一調用所有的行,方法fetch()取只有當前行並將指針移動到下一行。

可以找到方法fetch()的文檔here和方法fetchAll的文檔可以找到here

1

檢查,如果在數據庫中輸入的電子郵件,

$stmt = $db->dbh->prepare("SELECT 1 FROM $this->table WHERE email= ?"); 
$stmt->execute([$email]); 
return $stmt->fetchColumn();