2013-01-12 113 views
0

我已經退出了PHP循環一段時間,當我返回時,昨天,我很快發現許多舊的PHP函數與mysql交互正在被淘汰。這很好,但我真的很苦惱與新的pdo代碼。比方說,用戶將要登錄,我想看看他的用戶名/密碼組合是否正確。然後,我想更新他的登錄計數,將他上次登錄的日期/時間移至'previouslogin'並使用當前日期/時間更新'lastlogin'。我遇到的問題。我無法獲得logincount增量,甚至沒有變量,我不能將lastlogin分配給變量,這使我無法更新previouslogin。你能告訴我我做錯了什麼嗎?php插入,查找,更新與mysql

public function accountLogin() 
{ 
    $sql = "SELECT UserID, UserName, PositionID, LoginCount, LastLogin 
      FROM users 
      WHERE UserName=:user 
      AND Password=:pass 
      LIMIT 1"; 
    try 
    { 
     $stmt = $this->_db->prepare($sql); 
     $stmt->bindParam(':user', $_POST['username'], PDO::PARAM_STR); 
     $stmt->bindParam(':pass', $_POST['password'], PDO::PARAM_STR); 
     $stmt->execute(); 
     if($stmt->rowCount()==1) 
     { 
      $_SESSION['Username'] = htmlentities($_POST['username'], ENT_QUOTES); 
      $_SESSION['LoggedIn'] = 1; 
      $_SESSION['UserID']= $stmt->fetch()[0]; 
      $_SESSION['PositionID']= $stmt->fetch()[2];         
      $logincount= $stmt->fetch()[3]; 
      $lastlogin= $stmt->fetch()[4]; 
      $sql = "UPDATE users SET LoginCount = ". $logincount + 1 . ", 
      PreviousLogin = " . $lastlogin ." 
      WHERE UserID = " . $_SESSION['UserID']; 

      $stmt = $this->_db->exec($sql); 

      return TRUE; 
+1

您已經安裝了什麼你的代碼只使用PHP 5.4的工作? –

+0

已安裝php 5.4。它工作的一半,但我不能將PreviousLogin設置爲lastlogin,並且我的mysql表不會將lastlogin更新爲當前時間戳,即使登錄計數正在增加。 – riley3131

回答

1

要通過一個遞增的MySQL場,你可以做LoginCount = LoginCount + 1

public function accountLogin() 
{ 
    $sql = "SELECT UserID, UserName, PositionID, LoginCount, LastLogin 
     FROM users 
     WHERE UserName=:user 
     AND Password=:pass 
     LIMIT 1"; 
try 
{ 
    $stmt = $this->_db->prepare($sql); 
    $stmt->bindParam(':user', $_POST['username'], PDO::PARAM_STR); 
    $stmt->bindParam(':pass', $_POST['password'], PDO::PARAM_STR); 
    $stmt->execute(); 
    if($stmt->rowCount()==1) 
    { 
     $row = $stmt->fetch(PDO::FETCH_OB); 
     $_SESSION['Username'] = htmlentities($row->UserName, ENT_QUOTES, "UTF-8"); 
     $_SESSION['LoggedIn'] = 1; 
     $_SESSION['UserID']= $row->UserID; 
     $_SESSION['PositionID']= $row->PositionID;         
     $lastlogin= $row->LastLogin; 
     $sql = "UPDATE users SET LoginCount = LoginCount + 1, 
     PreviousLogin = " . $lastlogin ." 
     WHERE UserID = " . $_SESSION['UserID']; 

     $stmt = $this->_db->exec($sql); 

     return TRUE; 
+0

謝謝,這很有幫助。 – riley3131