0

我已经离开 PHP 循环有一段时间了,当我昨天回来时,我很快发现许多与 mysql 交互的旧 php 函数正在逐步淘汰。这很好,但我真的在为新的 pdo 代码苦苦挣扎。假设一个用户要登录,我想看看他的用户名/密码组合是否正确。然后我想更新他的登录计数,将他上次登录的日期/时间移动到“previouslogin”并用当前日期/时间更新“lastlogin”。我遇到的问题。我无法使登录计数增加,甚至变量也无法增加,我无法将 lastlogin 分配给变量,这使我无法更新以前的登录。你能告诉我我做错了什么吗?

    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;
4

1 回答 1

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;
于 2013-01-12T21:54:37.653 回答