Online Status for Multiple Users - php

I was able to do online status but works only for one user. When I login, it shows all users on users.php online even when they are offline.
Here is the Status Code:
session_start();
include_once 'db_connect.php' ;
if(isset($_SESSION['users'])) {
$setLogged= mysql_query("UPDATE `users` SET `lastlogin` = '$last' WHERE `id` = '".$_SESSION['users']."'") or die(mysql_error());
}
$last = strtotime(date('Y-m-d H:s'));
$loggedtime = time() - 300; // 5 minutes
if($last > $loggedtime) {
echo '<font color="green" size="3px">online</font>';
} else {
echo '<font color="red" size="3px">offline</font>';
}
?>
I need help on how to make it work for multiple users.
Thanks. ;)

You have to use something like this:
$query=mysql_query("SELECT id FROM users WHERE last_login>NOW()-INTERVAL 30 MIN");
while($array=mysql_fetch_assoc($query)){
//Do something with the id's or the info you get for user who have there last login
//in the last 30mins
}
As #Crisp says in the comment above your query for last_login should be updated too, you can use mysql now() function like this:
$setLogged= mysql_query("UPDATE `users` SET `lastlogin` = NOW() WHERE `id` = '".$_SESSION['users']."'") or die(mysql_error());
Note you have to stop using mysql_* as these functions are deprecated, start using PDO or mysqli

Related

Adding a timestamp into mySQL table

I am very new into LAMP environment and wanted to add the timestamp into the mysql table every-time any user logs into the system but I am having some typo issues. Part of my index.php file is below. Thanks!
if ($uname != "" && $password != ""){
$sql_query = "select count(*) as cntUser from users where username='".$uname."' and password='".$password."'";
$result = mysqli_query($con,$sql_query);
$row = mysqli_fetch_array($result);
$count = $row['cntUser'];
if($count > 0)
{
$_SESSION['uname'] = $uname;
**$timestamper = "UPDATE 'users' SET timestamp = CURRENT_TIMESTAMP() WHERE username='".$uname."'";
mysql_query($timestamper);
header('Location: home.php');**
}
else
{
echo "Invalid username and password";
}
}
My table looks like this: https://imgur.com/a/fblTkpY
Seems that you should have to alter your database schema also.
Let me explain you,
First add below columns to your db
is_login (datatype (enum) with values 0/1 )
last_login_datetime (datatype (timestamp), attibutes (on update current timestamp), default (current timestamp) )
Now when user logs in the system, set is_login flag to one and at the same time system will automatically update your last_login_datetime,
with the help of this, if future you can also use this is_login field in many terms and this will help you alot.

How do I logout users that have been afk for 10 minutes?

I wrote this script but it doesnt seem to work. even tho mysqli_num_rows is > 1, no user get logged out.
online=0 = user is offline.
<?php
include_once 'db.php';
$res = mysqli_query($con, "SELECT username FROM users WHERE last_active<= NOW() - INTERVAL 10 MINUTE");
$row=mysqli_fetch_array($res);
$user = $row['username'];
mysqli_query($con, "UPDATE users SET online=0 WHERE username='$user'");
?>
You could just run a query like this:
"UPDATE users SET online = 0 WHERE last_active<= NOW() - INTERVAL 10
MINUTE"
oh, assuming you have code somewhere else that will actually put them "offline" if their online field = 0...

Insert query not working with MySQL

I don't know if wrote something wrong in the query, or if it's a logic error. The problem is on the second to last line.
<?php
include "connectdb.php";
$userId = mysql_real_escape_string($_GET["userId"]);
$q1 = mysql_query("SELECT * FROM visitors WHERE userId='userId'");
$num = mysql_num_rows($q1);
if($num==1){
//user exists, update visits and unique values
$visits = 0;
while($row=mysql_fetch_array($q1)){
$visits = $row["visits"] + 1;
echo $row["visits"] + 1;
}
mysql_query("UPDATE visitors SET visits='$visits',unique='no' WHERE userId='$userId'");
die();
}
//if there is no current visitor
mysql_query("INSERT INTO visitors(userId,visits,unique) VALUES('$userId','1','yes')");
?>
EDIT: userId and visits are both set to INT in the database.
i think first error in in variable name using in $ql and second is $num==1 if in visitors table multiple record of thats user then this condition will be wrong ($num==1) so i think replace it with this ($num>0)
<?php
include "connectdb.php";
$userId = mysql_real_escape_string($_GET["userId"]);
$q1 = mysql_query("SELECT * FROM visitors WHERE userId='$userId' ");
$num = mysql_num_rows($q1);
if($num>0)
{
//user exists, update visits and unique values
$visits = 0;
while($row=mysql_fetch_array($q1))
{
$visits = $row["visits"] + 1;
echo $row["visits"] + 1;
}
mysql_query("UPDATE visitors SET visits='$visits',unique='no' WHERE userId='$userId'");
die();
}
//if there is no current visitor
mysql_query("INSERT INTO visitors(`userId`,`visits`,`unique`) VALUES ('$userId','1','yes') ");
?>
You should add error handling to your sql queries, but the problem (after the correction indicated by #DanielLisik) is the use of a reserved word: unique.
Change your query to:
mysql_query("INSERT INTO visitors(userId,visits,`unique`) VALUES('$userId','1','yes')");
You should also consider changing to PDO or mysqli as the mysql_* functions are deprecated.
1.
Change:
$q1 = mysql_query("SELECT * FROM visitors WHERE userId='userId'");
to:
$q1 = mysql_query("SELECT * FROM visitors WHERE userId=$userId");
2.
Delete the single quotes around $userId in your SQL queries (since it's an INT). It should be like this:
mysql_query("UPDATE visitors SET visits='$visits',`unique`='no' WHERE userId=$userId");
and:
mysql_query("INSERT INTO visitors(userId,visits,`unique`) VALUES($userId,'1','yes')");

Setting time limit php

I am trying to set time limit in reservation system. Such that Users must
have the ability to remove their bookings, but not before the lapse of 1 minute away from the time when the booking has been entered
<?php
require_once 'connection.php';
if(isset($_SESSION['book'])){
if (isset($_SESSION['book_time'])){
if (time()-$_SESSION['book_time']>= 60){
if (isset($_POST['delete'])){
$machineID = $_POST['machine_id'];
$starttime = $_POST['start_time'];
$qry = "DELETE FROM bookings where machine_id = '$machineID' AND start_time = '$starttime'";
$result = mysql_query($qry,$conn);
if ($result){
if(mysql_affected_rows()>0){
$message[] = 'Booking Deleted form DB';
}
}
}
}
}
}
?>
but it couldn't remove even after 1 min with this script....what could be possible problem
Possible problems:
$_SESSION['book'] or $_SESSION['book_time'] or $_POST['delete'] is NULL
$machineID contains not exists ID
$starttime contains wrong time or time in wrong format
Try to dump this variables. If they are ok try to run query manualy.

PHP works first time then fails

Basically what this does is makes it so after the user presses a button, they have to wait 2 minutes to press it again. When you press it the first time, it works, then if you press it again before 2 minutes, it says "please wait 2 minutes." but after 2 minutes, you can press it as many times as you like without the error, not what I want. Here is the code
<?php
if('sub') {
$client = $_SERVER['REMOTE_ADDR'];
$username="user";
$password="pass";
$database="db";
mysql_connect(localhost,$username,$password);
$time = strtotime("2 minutes");
$now = strtotime("now");
#mysql_select_db($database) or die( "Unable to select database");
$query = "SELECT Time FROM log WHERE IP='$client'";
$result= mysql_query($query);
$num=mysql_num_rows($result);
while($rows=mysql_fetch_array($result)){
$timestamp = $rows['Time'];
}
echo n;
echo $now;
echo t;
echo $timestamp;
if($now < $timestamp)
{
echo "<center><h2 style=\"color:red\" class=\"texts\" id=\"homeLink\">Please wait 2 minutes.</h2></center>";
}
else{
//some other code
$query1 = "INSERT INTO log VALUES ('$client','$time','$username')";
$query2 = "UPDATE `log` SET `Time`='$time' SET `Username`='$username' WHERE `IP`='$client'";
if($num == 0)
{
mysql_query($query1);
}
else
{
mysql_query($query2);
}
mysql_close();
}
?>
As you can see, if there is no row for the IP of the user, it makes a new one, if there is it will update it. After the first time, it no longer works. Hope someone can help. Thanks!
Your update statement is a bit off, so the update fails;
UPDATE `log` SET `Time`='$time' SET `Username`='$username' WHERE `IP`='$client'"
You should only use SET once, like this;
UPDATE `log` SET `Time`='$time', `Username`='$username' WHERE `IP`='$client'"
I'm pretty sure your database does not contain entries you think it contains. Can you check it (IPs and stuff on after button press)?

Categories