简体   繁体   中英

How do I update a mysql table when a visitor leaves the web page?

Here is my problem.

So, I am trying to make my page so that when somone visits the page with PHP

if ($_SESSION['signed_in'] == true){
    $sql = "UPDATE
            users
        SET
            user_status = 1
        WHERE
            user_id = " . $_SESSION['user_id'] . "";
    $result = mysql_query($sql);
    if (!$result){
    echo 'fix me!';
    }else{
    }
}

Now!

When the user exits or goes to a new page I want the user_status to be set back to 0 so when the user enters the site that already has a signed in session it goes back to 1.

How would I get to doing that with PHP or javaScript? Because even if I have a logout button people will still click exit and they will be logged in forever until they log in and log back out.

If by leaving you mean using an link on your page, you could just add some server side handling before that. (using a script which changes the status, then does the redirect)

If you mean leaving by entering another address etc., you could still use the window.unload event to trigger an ajax call before that.

https://developer.mozilla.org/en-US/docs/Web/API/Window.onunload

why dont you use the unload method on your form so that when the user is closing the site, the unload method will be called and then you can set the counter to 0 again.

<form onUnload="set0.php">

you can do something like that. 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