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.)
Related
I'm writing a time logging programme for a client who is a piano tuner, and I've written the following PHP code to give a record a status of 'to do':
$last_tuned = '2017-01-05';
$tuning_period = 3;
$month_last_tuned = date('Y-m', strtotime(date('Y-m-d', strtotime($last_tuned))));
$next_tuning = date('Y-m', strtotime($month_last_tuned.(' +'.$tuning_period.' months')));
if (time() > strtotime($next_tuning.' -1 months')) {
if (time() > strtotime($next_tuning)) {
return 'late';
} else {
return 'upcoming';
}
}
As you can see, the $last_tuned variable is of the date(YYYY-MM-DD) format. This is then converted to a (YYYY-MM) format.
Once convered, an additional number of months, identical to $tuning_period is then added to the $month_last_tuned variable giving us a month and year value for when we need to add a new record.
If the current time (found with time()) is greater than the $next_tuning variable - 1 month, it returns that the task is upcoming. If it's after the $next_tuning variable, it returns that the task is late.
I now have to write a MySQL query to list the items that would return as upcoming or late.
How would I write this in MySQL? I'm not very good with MySQL functions, and some help would be much appreciated.
My attempt at the logic is:
SELECT * FROM records
// The next lines are to get the most recent month_last_tuned value and add the tuning_period variable
WHERE
NOW() > (SELECT tuning_date FROM tunings ORDER BY tuning_date ASC LIMIT 1)
+
(SELECT tuning_period FROM records WHERE records.id = INITIAL CUSTOMER ID)
I know that that is completely wrong. The logic is pretty much there though.
My database schema is as follows:
I expect the rows returned from the query to be on-par with the 'late' or 'upcoming' values in the PHP Code above. This means that the rows returned will be within 1 months of their next tuning date (calculated from last tuning plus tuning period).
Thanks!
You'd probably be better off with using the DateTime object instead of manipulating date strings.
$last_tuned = '2017-01-05';
$tuning_period = 3; // months
$dt_last_tuned = DateTimeImmutable::createFromFormat('Y-m-d',$last_tuned);
$dt_next_tuning = $dt_last_tuned->add(new DateInterval('P3M'));
$dt_now = new DateTimeImmutable();
$dt_tuning_upcoming = $dt_next_tuning->sub(new DateInterval('P1M'));
if( $dt_now > $dt_next_tuning) {
return 'late';
}
if( $dt_now > $dt_tuning_upcoming) {
return 'upcoming';
}
You can also use these DateTime objects in your MySQL queries, by building the query and passing through something like $dt_next_tuning->format('Y-m-d H:i:s'); as needed.
Given your table structure, however, it may be easier to just get all the relevant records and process them. It's a little difficult to tell exactly how the pieces fit together, but generally speaking MySQL shouldn't be used for "processing" stuff.
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.
I have some data in my table which are [name][address][phone_number] and the date in this format 2015-10-14 14:37:38. I am using php PDO. How can I query out just today date from the table?
The following code is my code to query out result for the past 7 days which worked perfectly. However, whenever I replace it with 1 it doesn't work:
$query = $digital->query('SELECT * FROM sales WHERE `datetime` BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW() ORDER BY sale_id DESC');
What I want is to be able to query out all today data inserted into database.
You can use this, haven't tested.
<?php
$todaysDate = date('Y-m-d'); //if your date is stored in y-m-d format
try
{
$s = $conn->query("SELECT * from sales where datetime LIKE '%$todaysDate%'");
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$results = $s->fetch(PDO::FETCH_OBJ);
?>
Your query results is now in $results variable.
Extended version
<?php
try
{
$s = $conn->query("SELECT * from sales");
}
catch(PDOException $e)
{
echo $e->getMessage();
}
while($results = $s->fetch(PDO::FETCH_OBJ))
{
$date = explode(" ", $results->datetime);
if($date[0] == date('Y-m-d'))
{
//write code here to display data
}
}
?>
Make sure you replace all the columnNames and tablename.
Edit :-
Here's a sqlfiddle pertaining to my first solution.
http://sqlfiddle.com/#!9/7c2f1/3
I dont know whether it applies to PDO, as I'm not very acquainted to it, but I use to pass the date in a var, then ask for a match in my sql statement
// choose your own timezone here
date_default_timezone_set('America/Sao_Paulo');
// then define your variable as the current time:
$date = date("Y-m-d H:i:s");
then, i'd use the correct PDO syntax to compare the column with the var (a simple "where" statement should do it).
(using codeigniter syntax)
$this->db->where('date', $date);
this has held me up all day i have a column called hours where i add up hours (not clock time) I have a method which takes one date from the other (starttime -endtime) but when i try and update a entry with the hours it wont work bellow is my code.
private function calculatedifference($starttime,$endtime) // delete checkin time from checkouttime
{
$diff= abs(strtotime($starttime) - strtotime($endtime));
return date("H:i:s",$diff);
}
i then proceed to try and update a row based on a users email and their starttime. but it doesnt work? below are my methods in my model to update the entry and the line of code i use to call that method.
function update_daily_row($email,$date,$data)//update existing row.
{
$this->db->where('email', $email);
$this->db->where('starttime', time($date));
$this->db->update('dailyinfo', $data);
}
here is where i call the method.
$hours=$this->calculatedifference(date("Y-m-d H:i:s",
$this->session->userdata
('last_activity')),date("Y-m-d H:i:s"));
$data =array("hours"=>$hours,"endtime"=>date("Y-m-d H:i:s"));
$this->dbaccess->update_daily_row
($this->cdata['email'],
date("Y-m-d H:i:s",
$this->session->userdata('last_activity')),$data);
any help would be appreciated as ive actually gone blind from looking at the thing
update: so i checked the query using this command
$this->db->last_query();
returned the query the email address missing? that means active record probably doesnt like the format of the email address. is there anyway around this?
my query returns after using this method as
UPDATE `dailyinfo` SET `endtime` = '2013-10-02 21:14:02',
`hours` = '00:00:03' WHERE `email` = ''AND `starttime` = '2013-10-02 21:13:59'
so the email is always blank. not sure how to fix this???
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.