简体   繁体   中英

PHP and MySQL - how to update single row from single table using order by desc and limit 1

Hello guys actually i am trying to maintain user logs with ip, last login time and last logout time of users, working in php and mysql. successfully stored ip and login time while user logs in but while updating logout time at the time of logout it updated all logout time for the same user id and i want to update only last logout time of the user id whether he logged in any no of times. can any one help me for the same.

my code is -

if (isset($_SESSION['userId']) && !empty($_SESSION['userId'])) {
    include "connection.php";
    $userId = $_SESSION['userId'];

    $sqluserlogs = "UPDATE userlogs SET LastLogout = now()
    WHERE uid = '$userId' ORDER BY uid DESC LIMIT 1";

    if (mysql_query($sqluserlogs, $conn)) {
        //echo 'success';
    } else {
        //echo 'failed';
    }
}

updated query -

  $sqluserlogs = "UPDATE userlogs SET LastLogout = now() WHERE
   uid = '$userId' ORDER BY ulogID DESC LIMIT 1";

Thanks in advance

Try a join:

 "UPDATE userlogs AS UpdateTable
     INNER JOIN (
         SELECT JoinTable.id
         FROM userlogs AS JoinTable
         WHERE JoinTable.uid = '$userId'
         ORDER BY uid DESC
         LIMIT 1) 
                 AS source ON source.id = UpdateTable.id
    SET LastLogout = now()";

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