Hi since 3 hour I am trying to make this work but not getting the result as I want. I want to display user list with online and offline status.
Here is the table
and here what I tried to get status result.
$loggedtime = time() - 300; // 5 minutes
$query = 'SELECT userid, handle FROM ^users WHERE loggedin = '.$loggedtime.' ORDER BY userid ASC';
// below are scripts function qa_ pleses refer this http://www.question2answer.org/functions.php
$result = qa_db_query_sub($query);
$users = qa_db_read_all_assoc($result);
$row = mysql_fetch_array($result);
if($row['userid'] > $loggedtime){
echo $row['handle'].' is online';
} else {
echo $row['handle'].' is offline';
}
NOT THIS TOO
foreach($users as $user){
if($user['userid'] > $loggedtime){
echo $user['handle']. ' is online';
} else {
echo $row['handle'].' is offline';
}
}
None of above code working. I am new to MYSQL and PHP just know basic so please help me to solve this.
EDIT:
I have tried now this but not working
foreach($users as $user){
if($user['loggedin'] > $loggedtime){
echo $user['handle']. ' is online';
} else {
echo $row['handle'].' is offline';
}
}
EDIT 2
$query = "SELECT
userid, handle,
CASE
WHEN TIMESTAMPDIFF(SECOND, loggedin, NOW()) < 300
THEN 'Online'
ELSE 'Offline'
END AS 'status'
FROM ^users
ORDER BY userid";
$result = qa_db_query_sub($query);
while($user = mysql_fetch_array($result)){
echo $user['handle'] . '<BR/>';
}
NEW APPROACH
Please check this for new approach User online offline status - offline status issue
Since you fixed the user id comparison, let's address the next issue..
You're trying to compare a string DATE versus a unix timestamp. Let's make them the same type and compare:
foreach($users as $user)
{
$user_time = strtotime($user['loggedin']);
if($user_time > $loggedtime)
{
echo $user['handle']. ' is online';
} else {
echo $row['handle'].' is offline';
}
}
Overall not the best way to approach this problem, but it might get this working for you. The database solution above is probably best.
Your structure looks funny to answer the question. Your loggedin field actually looks more like a "the last time they logged in". Just because you know when they logged in doesn't necessarily mean they are "online".
The reason your query isn't working is because you are comparing a UNIX timestamp to a mysql datetime. In addition, you are using = so unless they logged in EXACTLY five minutes ago, this will not work.
At minimum.
SELECT userid, handle FROM ^users WHERE loggedin > '.date('Y-m-d h:i:s', time()-300).'ORDER BY....
Why not just check on the database side?
SELECT
userid, handle,
CASE
WHEN TIMESTAMPDIFF(SECOND, loggedin, NOW()) < 300
THEN 'Online'
ELSE 'Offline'
END AS 'status'
FROM ^users
ORDER BY userid
You can use TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2) to return datetime_expr2 – datetime_expr1, where datetime_expr1 and datetime_expr2 are date or datetime expressions. One expression may be a date and the other a datetime; a date value is treated as a datetime having the time part '00:00:00' where necessary. The unit for the result (an integer) is given by the unit argument. The legal values for unit are the same as those listed in the description of the TIMESTAMPADD() function.
Take a look at the MySQL Date and Time Functions.
Also, I strongly advise using reserved words for table names.
Related
I have in my MSSQL database a column with datatype of datetime which contains some dates in this format 2021-01-11 19:58:04.277.
This is a voting system, the idea is that the users can only vote once every 24 hours.
Every time they vote this table is updated with a new record and a new date is added with the corresponding user.
I want to display a message that says how many hours left to place the next vote.
This is the code I am trying to use:
/**
* Get Votes Time
*
*/
public function getVoteRemainingTime($account) {
date_default_timezone_get();
$currentTime = date('Y-m-d H:i:s');
$sql = "SELECT VoteDate FROM dbo.vote WHERE Account = :account ORDER BY logid DESC";
$query = $this->db->prepare($sql);
$query->execute(array(':account' => $account));
$voteDate = $query->fetch(PDO::FETCH_OBJ);
$timeLeftVote = strtotime($currentTime) - strtotime($voteDate->VoteDate);
if($timeLeftVote > 86400) {
return '<strong>Vote Available!</strong>';
} else {
return $timeLeftVote;
}
}
But it is displaying the wrong information. What I am doing wrong? I would appreciate your help.
Thanks!
you need declare format parameter of the date() like date('Y-m-d H:i:s')
date_default_timezone_get();
$currentTime = date('Y-m-d H:i:s');
$timeLeftVote = strtotime($currentTime) - strtotime('2021-01-11 19:58:04.277');
if($timeLeftVote > 86400){
echo 'Vote available';
}else{
echo $timeLeftVote;
}
Instead of SELECT VoteDate FROM dbo.vote
Can you do the calculation on the time difference at source in the database using
SELECT VoteDate, DATEDIFF(HOUR, VoteDate, GETDATE()) as HourDifference from dbo.vote
As I cannot check your database query, I only checked the rest of the code and it seems to work (as Fikri F mentioned in the comments of this post) if I replace $voteDate->VoteDate by a static date.
So please provide more information. You could output the current time and the previous vote time from the database as strings, and for both dates as well the result of strtotime, and in the end the result of the method. Then please explain, what the wrong behaviour is. By this, we can narrow down the problem either to the DB query or to the PHP code.
(I would write this as a comment, but I have not enough reputation.)
I've developed a bidding system with PHP and MySQL.
It works good in the most of the cases, but I've noticed there is a problem when offers are really close.
$now = DateTime::createFromFormat('U.u', microtime(true));
$dateMicroTime = date("Y-m-d H:i:s").".".$now->format("u");
$amountToRaise = 100;
$lastOffer = $bid->lastOffer();
//if there is an offer yet
if($lastOffer){
$newPrice = $lastOffer->getAmount()+$amountToRaise;
//else is the first offer
}else{
$newPrice = $amountToRaise;
}
//if the user is not the last bidder
if($user->getId() != $lastOffer->getUserId()){
$bidOffer = new BidOffer();
$bidOffer->setBidId($bid->getId());
$bidOffer->setUserId($user->getId());
$bidOffer->setAmount($newPrice);
$bidOffer->setTime($dateMicroTime);
$bidOffer->save();
//if this is not the first offer I give back the money to the previous user
if($lastOffer){
$lastUser = $lastOffer->user();
$lastUser->setCash($lastUser->getCash()+$lastOffer->getAmount());
$lastUser->save();
}
}
The code works well when offers are done in different moments, but users offer in the same seconds for example: 18:00:01.1299022 and 18:00.02.1222377
The user with previous offer doesn't receive back the offer.
How can I fix this? I've tried to use a temporary variable to block the statement temporary until every query are executed, but no success.
I would separate dateTime from microtime and would not use $dateMicroTime = date("Y-m-d H:i:s").".".$now->format("u");.
You can than use microtime to extract the last bidder. This can be done by adding a bid_utime column in your DB. If you are looking all the bidders for one auction chronologically ORDER BY table.bid_utime DESC.Last bidder can be found by ORDER BY table.bid_utime DESC LIMIT 1 as a return from $lastOffer = $bid->lastOffer();.
This also means you wont be saving your bids with: $bidOffer->setTime($dateMicroTime);but with something like:
$bidOffer->setDate($date); and $bidOffer->set_uTime($now);
But you can also skip all of this and return only the last entry from the bid table with SELECT * FROM bid_Table ORDER BY ID DESC LIMIT 1 and forget about dateMicroTime and microtime. Hope this helps.
i'm saving time for first login ,now when user logs in i enter time using NOW() function, that saves time in this format (data type is DATETIME.
2015-12-24 15:47:30
Now logic is like every login is first login so i've to check if there already exists an entry for today to check that i fetch time explode it and get time like this
$logintime= mysqli_query($connection,"SELECT loggedin from employees");
$loggedin_time= mysqli_fetch_assoc($logintime);
$Date = $loggedin_time['loggedin'];
$loggedin_time_converted= explode(" ",$yourDate) ;
$ConvertedDate = $loggedin_time_converted[0];
last line returns 2015-12-24 now i've date
$today= time();
$DateToday= date("Y-m-d",$today);
$DateToday also returns me same format and same date now i need your help me to compare these dates , if they are equel i dont uopdate database if they are not i will , Pleas help me how do i compare these values
You can do the test in MySQL
$result = mysqli_query($connection, "SELECT DATE(loggedin) = CURDATE() AS logged_in_today FROM employees");
$row = mysqli_fetch_assoc($result);
if (!$row['logged_in_today']) {
// code to update database
}
Wow, you've done all the hard stuff to get the problem to the point of being a simple comparison of 2 strings. This is all you need to do to get over the finish line ...
if ($ConvertedDate !== $DateToday) {
// update the database
}
You can use Php Built In function "Date Difference."
Code Seems Like As Follow:-
$today= time();
$DateToday= date("Y-m-d",$today);
$diff = date_diff($today,$DateToday);
echo "$diff days";
This will return values something like +12 days or something else.
Pulling my hair out on this, it has to be obvious, but I can't see it today.
I built a small monitoring tool for an app we have. I want to do a check in the DB to make sure the backend scripts are working and the data isn't stale by more than 15 min. When no records are returned in a certain timeframe it should pop up a message saying to check the script. If they are not returned it should be an empty dataset and I should get a message on it.
Problem is, I can't get empty() or !isset to work. Actually regardless of whether I use !empty(), empty(), isset() or !isset(), my $tripped variable never gets tripped. I have this working for other alerts, but this one seems to be stubborn and I don't see what I'm missing.
PS I know mysql_ is out of date.
The relevant piece of code:
$ldap_check = mysql_query("SELECT
*
FROM ldap_conns
WHERE DATETIME > DATE_SUB(NOW(), INTERVAL 15 MINUTE)
order by DATETIME DESC
LIMIT 1");
while($row = mysql_fetch_array($ldap_check))
{
if (empty($row['DATETIME']))
{
echo '<b><font color=blue>Stale Data: </font> <font color=red>LDAP data is old, check script!</font><br>' . $row['DATETIME'];
$tripped='Yes';
}
}
if ($tripped!='Yes')
{
echo '<b><font color=blue>Stale Data: ' . $row['DATETIME'] . '</font></b> <font color=green> No Problems Found<br></font>';
}
You are doing it wrong... Want just check if there exists any old items? Use count! There is no reason for selectin g ALL fields from ALL records from the table. This is wrong using of database! Use count, and make index on DATETIME field!
$result = mysql_query("SELECT
count(*) old_items
FROM
ldap_conns
WHERE
DATETIME < DATE_SUB(NOW(), INTERVAL 15 MINUTE)");
$row = mysql_fetch_row($result);
if ($row['old_items']) {
echo 'There is '.$row['old_items'].' old items!';
}
You have this condition in your query:
WHERE DATETIME > DATE_SUB(NOW(), INTERVAL 15 MINUTE)
So I don't see how $row['DATETIME'] could ever be empty for any of the rows fetched (although you are actually only fetching one row...).
Trying to figure out why my code isn't working. Basically I have an elseif statment like so:
mysql_connect("localhost","xxxx","xxxxx");
mysql_select_db("xxxxxx");
$sql = "SELECT COUNT(DATE) FROM calendar";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$checkdate = $row['DATE'];
$DATEFROM = $_POST['DATEFROM'];
$DAYCOUNT = $_POST['DAYCOUNT'];
$DAYS = $_POST['DAYS'];
if ( $DAYCOUNT < $DAYS ) {
header( 'Location: request_go_fail.php' );
}
else if ( $checkdate == $DATEFROM ) {
echo "FAIL!";
}
else {
It doesn't work, the first check (to see if the DAYCOUNT is less than DAYS works fine, but when comparing to entries in the DB it doesn't seem to do it. Seems to be some issue with finding the already existing data, as when I change $checkdate to an entry that's already in the database it works great.
Any help is most appreciated :)
SELECT COUNT(DATE) FROM calendar doesn't return a field called date, print_r the $row variable to confirm that. Best solution is to change the statement to something like SELECT COUNT(DATE) AS datecount FROM calendar and then do $checkdate = $row['datecount'];
But while rereading your code fragment, I'm not sure that you really want the count of DATE's in the calendar table, and what exactly the intention is, is hard to determine from the code fragment.
Also, DATE is a reserved word in SQL, not the optimal choice for a column name!
Did you try printing $checkdate? I suspect it's null if that is indeed the SQL you're using.
Should be $row['COUNT(DATE)'] I believe, or you can use mysql_fetch_array and $row[0] instead, or use an AS in your SQL or
$checkdate = mysql_result($result, 0);
And skip the fetch call all together.
COUNT(DATE) will return the number of non-null DATE fields in your DB btw, is that really what you want?
You don't have a DATE key in the $row variable because of the sql command. Use this instead, it's called Alias:
SELECT COUNT(DATE) AS DATE_COUNT FROM calendar
Now you have a key DATE_COUNT which will contains value.
$checkdate = $row['DATE_COUNT'];