简体   繁体   中英

Query working on second attempt but not first

I want to track when users last logged in, so i have added a column in my database that is time stamped and can be updated every time they log in, and added an update into the login function, but when i login i get an error saying 'SQLSTATE[HY000]: General error' and nothing happens to my database, but if i click login again it logs me in fine and updates the table as i wanted. Here is my login function:

public function login($email,$upass)
{
    try
    {
        $stmt = $this->conn->prepare("SELECT * FROM po_users WHERE userEmail=:email_id ");
        $stmt->execute(array(":email_id"=>$email));
        $userRow=$stmt->fetch(PDO::FETCH_ASSOC);

        if($stmt->rowCount() == 1)
        {
            if($userRow['userStatus']=="Y")
            {
                if($userRow['userPass']==md5($upass))
                {

                    $_SESSION['userSession'] = $userRow['userID'];
                    $stmt = $this->conn->prepare("UPDATE po_users SET lastLogIn = current_timestamp WHERE userEmail=:email_id");
                    $stmt->execute(array(":email_id"=>$email));
                    $userRow=$stmt->fetchAll(PDO::FETCH_ASSOC);
                    return true;
                }

Any Ideas?

You actually can't use "fetchAll" after an update... So try this instead:

public function login($email,$upass) {
    try {
        $select_user_stmt = $this->conn->prepare("SELECT * FROM po_users WHERE userEmail=:email_id ");
        $select_user_stmt->execute(array(":email_id"=>$email));
        $userRow = $select_user_stmt->fetch(PDO::FETCH_ASSOC);

        if($select_user_stmt->rowCount() == 1) {
            if($userRow['userStatus']=="Y") {
                if($userRow['userPass'] == md5($upass)) {
                    $_SESSION['userSession'] = $userRow['userID'];
                    $update_user_stmt = $this->conn->prepare("UPDATE po_users SET lastLogIn = current_timestamp WHERE userEmail=:email_id");
                    $update_user_stmt->execute(array(":email_id"=>$email));
                    $select_user_stmt->execute(array(":email_id"=>$email)); // do a search again here...
                    $userRow = $select_user_stmt->fetch(PDO::FETCH_ASSOC);
                    return true;
                }

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM