how can see who's online using timestamp function? - php

i am having problem showing how many users are online using timestamp function. what i am doing is storing last active time in 'lastactivity' database column using time(); function and updating it whenever user refreshes the page. here's code for showing lastactivity :-
<?
$result = mysql_query("SELECT * FROM users");
while($array = mysql_fetch_array($result)){
$last = $array['lastactivity'];
echo $last;
}
?>
i am just confused what condition to use with 'if' if possible to seperate out those who are not active for more than 5 minutes.

MySQL can do it faster:
select * from users where timediff( now(), lastactivity ) > "00:05:00";

Related

Compare PHP current timestamp to timestamp in the database

As the title says.
From the database, in the resultset, I want those rows where the date and time (schedule column) are already passed.
In the database I have
On the PHP page I have:
$now = time();
$result = $mysqli->query("SELECT * FROM schedules WHERE $now >= UNIX_TIMESTAMP(schedule)");
However, if I test this on 2015-09-19 at 18:50:00, I get no results at all, while instead I should only get the row with ID 39.
As much as I know I am comparing two valid timestamps - the one generated by time() and the one converted from the database with UNIX_TIMESTAMP() - so what isn't working?
EDIT: I already tried to do
$result = $mysqli->query("SELECT * FROM schedules WHERE NOW() >= schedule");
But with no luck. I am getting the results with
while ($row = $result->fetch_assoc()) {
$id = $row['ID'];
echo $id;
}
Use now() to select rows where schedule is in the past
SELECT * FROM schedules WHERE now() > schedule
They are different because,
php time is based on the php timezone setting (inside php.ini).
database time is based on your system time (unless you set it).

redirecting user based on IP address and timestamp values

I need some more help with a script. I have pieced together the following from several examples but I'm falling short when it comes to comparing the results and the IP address and timestamp. As it stands, I'm trying to redirect a user to another page if they have accessed a certain area on my site for more then 10 minutes.
My MySQL table consists of the following columns:
ID, client_ip, submitted_time
Here's my current code:
<?php
$ipaddress = $_SERVER["REMOTE_ADDR"];
$link=mysqli_connect("localhost","root","password","visitors");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT count(`id`) AS 'count' FROM `visits` WHERE `client_ip` = '$ipaddress'
AND 'submitted_time' = CURRENT_TIMESTAMP - INTERVAL 10 MINUTE
LIMIT 1";
$result = mysql_query($link, $query);
if ($result['count'] > 0) {
echo "You have accessed this site in the last 10 minutes -- you are blocked!";}
else
{
echo "You have access";
exit;
}
?>
I should be getting the "You have accessed this site in the last 10 minutes echo..... But I'm getting You have access everytime. Any ideas on what I'm doing wrong based on my current code? Thanks in advance!
if you are checking whether they have accessed within the last 10 minutes you could use between
$query = "SELECT count(id) AS 'count' FROM visits WHERE client_ip = '$ipaddress'
AND 'submitted_time' BETWEEN CURRENT_TIMESTAMP - INTERVAL 10 MINUTE AND CURRENT_TIMESTAMP
although epends on the specifics of how you're trying to do it
Information about your schema & data type is insufficient. assuming submitted_time is DATETIME or TIMESTAMP,
you have two problem.
submitted_time is a column, so remove single quote, or use backtick.
use <= rather than =, user can revisit over 10+ minutes
LIMIT 1 is not required. COUNT(*) always return 1 record. but this is not problem..
below query would work well:
SELECT count(`id`) AS 'count'
FROM `visits`
WHERE `client_ip` = '$ipaddress'
AND `submitted_time` = CURRENT_TIMESTAMP - INTERVAL 10 MINUTE

How to only select row if table timestamp has been updated

Currently im selecting most updated row using the following php block, i have an ajax loop which runs this php block every few seconds to return feed. i want to echo false to ajax when latest timestamp hasn't changed so that ajax doesn't duplicate results and fill my Div (#feed) with identical content.
<?php
require_once 'db_conx.php';
$Result = mysql_query("SELECT * FROM profiles ORDER BY lastupdated desc limit 1") or die (mysql_error());
while($row = mysql_fetch_array($Result)){
echo $row['name'];
}
mysql_close($con);
?>
Somewhere in the session, or in the requestor, you need to store the last fetched time. It would be better to store it as a session variable (this I presume is client-specific because different clients will have loaded at different times) and then fetch all records that have their lastupdated time greater than the last_fetched time.
Everytime entries are fetched from the DB, just update the last_fetched variable to the current timestamp.
If you are running this every 5 seconds, I would do something like
$Result = mysql_query("SELECT * FROM profiles WHERE lastupdated > ADDTIME( NOW( ) , '-00:00:05.00000' ) ORDER BY lastupdated desc limit 1") or die (mysql_error());
$num_rows = mysql_num_rows($result);
if ($num_rows = 0) {
return false;
} else {
return true;
}
This will give you any rows that have been updated in the last 5 seconds, if it is older than this it should have been picked up in the last run.
Hope this helps
When you retrieve your results from the server I'm guessing you store the timestamp of the last query in some PHP variable in order to compare the returned results of the next query.
I would concatenate the timestamp into your query as a where clause so your sql query would become something like
$Result = mysql_query("SELECT * FROM profiles WHERE lastupdated > " . $timestamp . " ORDER BY lastupdated desc limit 1") or die (mysql_error());
It's also worth noting that when this executes if there has been more than one profile updated since the last update cycle then it will only return the most recently updated row.
Does this answer your question?

Displaying amount of users on a webpage

I am trying to write a PHP script that will count the amount of users that have visited the page within the last 10 minutes. This is my script right now:
function getOnlineUsers($database, $main_connection){
$database;
$visitor_id = session_id();
$timestamp = time();
$timeOut = $timestamp - 6000;
mysql_query("INSERT INTO online (m_time, ip) VALUES ('$timestamp', '$visitor_id')", $main_connection);
mysql_query("DELETE FROM online WHERE m_time < $timeOut");
$result = mysql_query("SELECT * FROM online");
mysql_fetch_assoc($result);
if(!$result){
$online_users = 1;
}else{
$online_users = mysql_num_rows($result);
}
return $online_users+1;
}
The problem is that nothing is being inserted into the database and the database remains empty and therefore the count is null. Can someone please assist me in this?
First, better use PDO or MySQLi. In your database, the 'm_time' column must be integer type, and pass the $timestamp value as number, not within quotes.
"INSERT INTO online (m_time, ip) VALUES ($timestamp, '$visitor_id')"
1) Change '$timestamp' to NOW(), mysql can't understand php's time() function ( assuming m_time is a datetime field) .
ie:
INSERT INTO online (m_time, ip)
VALUES ( NOW(), '$visitor_id')
2) Your delete suffers the same problem
3) You can use something a little more clever to get the users in the last 10 minutes, try something like:
select count(*) AS OnlineUserCount
from online
WHERE
m_time > DATE_SUB( NOW(), INTERVAL 10 MINUTE ) ;
Your code looks fine .. what i suggest you do is echo out the query when it runs and cope and paste it and run it directly from phpmyadmin and check if it gives you any error and if the row is inserted succesfully i suggest you check your connection file with the database.
And also try what's suggested by CoursesWeb

Need a More Specific PHP While Loop for Querying MySQL Database

I am querying a database and displaying data. I have a timestamp and a Facebook ID that I use to display the user's profile picture (using the Facebook graph). This is more of a PHP/Loop question than a FB Graph question though. Here's my bit of code that I'm working on:
$sql = "SELECT * FROM fb_id ORDER BY timestamp DESC";
$result = $mysqli->query($sql);
echo "<h1>".$lastone_month." ".$year_lastone."</h1>";
while($row = mysqli_fetch_array($result)){
$fb_id = $row['fb_id'];
$timestamp = date_parse($row['timestamp']);
$month = $timestamp['month'];
$year = $timestamp['year'];
echo "<a href='http://www.facebook.com/".$fb_id."' target='_blank'><img src='http://graph.facebook.com/".$fb_id."/picture/' /></a>";
}
Eseentially what happens is I'm echoing the most recent month (this is in a bit of code before this). $lastone_month is a number (it's the number of the month of the most recent user that signed up). Let's say that it's January so the h1 would display 1/2013. I then have the while loop looping through the database and echoing out the user's profile picture in order of timestamp. What I would like it to do is to run the while loop until it reaches a row where $month is not equal to $lastone_month.
I can't use "&& $month==$lastone_month in the while loop because the $month value is not declared yet at that point. I tried an if statement around the echo line but that caused it to infinitely display one entry. I tried to declare row before the while loop and then declare $month and $year there too and then run the loop but that didn't work either. I'm thinking it's a really simple solution but I can't figure out what it is. Any help would be greatly appreciated. Thanks so much!
You can use break to quit from loop at any point:
while ($row = mysqli_fetch_array ($result))
{
...
$month = $timestamp ['month'];
if ($month != $lastone_month) break;
...
}
But more efficient is to use WHERE in your SQL query:
$sql = "SELECT * FROM fb_id WHERE MONTH(timestamp)='$lastone_month' ORDER BY timestamp DESC";
// build here timestamp which is your limit and name it $limit
$sql = 'SELECT * FROM fb_id WHERE timestamp < "$limit" ORDER BY timestamp DESC';
Something like that

Categories