2013-12-19 74 views
0

中不起作用我試圖驗證PDO中的登錄,但它在函數內部時不起作用。我已經嘗試將$db添加到該函數中,但沒有幫助。無論發生什麼,它都會迴應「壞」,如果我將它從函數中刪除,它可以使用完全相同的代碼正常工作。這裏的整個事情:PDO在函數外部工作,在

function logIn($db) 
{ 
    try 
    { 
     $stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE Username = :user AND Usernameclean = :userclean AND Password = :pass"); 
     $stmt->bindParam(":user", $user); 
     $stmt->bindParam(":userclean", $userclean); 
     $stmt->bindParam(":pass", $pass); 
     $stmt->execute(); 
     $status = (bool) $stmt->fetchColumn(0); 
     if ($status) 
     { 
      echo "good"; 
     } 
     else 
     { 
      echo "bad"; 
     } 
    } 
    catch (PDOException $e) 
    { 
    echo "There was a problem connecting to this database."; 
    $e->getMessage(); 
    } 
} 
logIn($db); 

回答

1

您似乎沒有被傳遞$user$userclean$pass變量。 確保你將它們傳遞給你的函數(或者至少將它們全局化)

編輯:John擊敗了我!

3

你還記得你$db變量傳遞給函數,但忘了$user$userclean,並$pass所以他們不提供給你的函數(它們是超出範圍)。

還好,這是很容易解決:

function logIn($db, $user, $userclean, $pass) 
+0

謝謝!有史以來的第一個功能,所以我沒有弄清楚有一個範圍。精彩。 –

4

您還必須將您在函數中使用的其他變量傳遞給該函數。

所以,正確的功能是:

function logIn($db, $user, $userclean, $pass) 
{ 
    try 
    { 
     $stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE Username = :user AND Usernameclean = :userclean AND Password = :pass"); 
     $stmt->bindParam(":user", $user); 
     $stmt->bindParam(":userclean", $userclean); 
     $stmt->bindParam(":pass", $pass); 
     $stmt->execute(); 
     $status = (bool) $stmt->fetchColumn(0); 
     if ($status) 
     { 
      echo "good"; 
     } 
     else 
     { 
      echo "bad"; 
     } 
    } 
    catch (PDOException $e) 
    { 
    echo "There was a problem connecting to this database."; 
    $e->getMessage(); 
    } 
} 
logIn($db, $user, $userclean, $pass);