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).
Related
The only thing that I have left for my assignment is to show the amount of new transactions since the user last visited his statistics dashboard, I thought I understood the concept of this fairly well, but it seems like I'm running into a problem.
This problem is that the current-date that the user has, and the current-timestamp that the SQL uses are not one and the same. (I would assume this varies based on time-zones?)
I guess what I'm looking for is what time=zone MySQL stores the DATETIME (Current Timestamp) field in, so I can get the current time-stamp of the user, his time-zone, and attempt to perform logic to make them the same.
Or is there an easier way around this? I'm currently using the DATETIME format in my dashboard to display information on purchase dates, which is formatted like so 2015-01-12 01:02:18 inside of a table.
Perhaps my query is just wrong, who knows:
function getNewTransactions($connection, $user) {
$statement = $connection->prepare("SELECT `lastcheck` FROM `login` WHERE 1");
$statement->execute();
while($row = $statement->fetch()) {
$d = $row['lastcheck'];
}
$statement = $connection->prepare("SELECT * FROM `transactions` WHERE `date` > :d");
$statement->bindParam(":d", $d);
$statement->execute();
$transactions = 0;
while($row = $statement->fetch()) {
$transactions++;
}
$date = date("Y-m-d H:i:s");
$statement = $connection->prepare("UPDATE `login` SET `lastcheck` = '{$date}' WHERE `username`=:name");
$statement->bindParam(":name", $user);
$statement->execute();
return $transactions;
}
If I swap the > around to < it does show older transactions, but they're off by a few hours.
http://php.net/manual/en/function.date-default-timezone-set.php
This should help you out with setting the timezone.
You can get the timezone from MySql with
SELECT ##system_time_zone;
or get the +/- offset from GMT with
SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP);
In your situation you can try something like this
SELECT convert_tz(`lastcheck`, 'TIMEZONE_LASTCHECK_IS_STORED_IN', ##system_time_zone, ) as lastcheck
FROM `login`
WHERE 1
But ideally, all the datetimes in the database should be stored in the same timezone. That would eliminate your current problem. You could achieve this with ...
SELECT ##system_time_zone
... and save the value into the PHP variable $db_timezone_code
... then replace the $date assignment with ...
$db_timezone = new DateTimeZone($db_timezone_code);
$now = new DateTime('now');
$now->setTimeZone($db_timezone);
$date = $now->format('Y-m-d H:i:s');
... $date is now converted from the PHP servers timezone
... to the databases default timezone.
I want that my PHP checks if the time in the mysql db is the same, and if not that it will be changed.
This is what I got:
<?php
$last_time_check=mysqli_query($con,"SELECT `time` FROM `servervars`");
if((time()-$last_time_check) >=1)
{
mysqli_query($con, 'UPDATE `servervars` SET `time`='.$time.' WHERE ID=1');
}
?>
$con is the connection to the DB.
Current value 'time' in servervars: 1412448339
Value 'ID' is 1
I do something wrong, but I just cannot find where it's going wrong.
The Fix
I've removed the variable $last_time_check and only checked if the time could get changed. If this happends then it will send another message to the client.
mysqli_query($con, 'UPDATE `servervars` SET `time` = UNIX_TIMESTAMP() WHERE ID = 1 AND UNIX_TIMESTAMP() - `time` >= 1');
if ($con->affected_rows)
{
// at least 1 second has elapsed, do stuff
}
MySQL has an equivalent to time(), its the function UNIX_TIMESTAMP(). Differently though, it can take a DATETIME as parameter to convert it into UNIX time, but when used without parameters its the same as UNIX_TIMESTAMP(NOW()).
UPDATE servervars SET time = UNIX_TIMESTAMP() WHERE ID = 1
Update
Ok so about the other issues. You are doing it all wrong. mysqli_query does not return the value directly. To fetch the value of time from the database, you need 3 steps:
$result = $con->query('SELECT `time` FROM `servervars` WHERE ID = 1'); // fetch result set
$row = $result->fetch_row(); // fetch a row from the result set, as an array
$last = $row[0]; // get the first element from the row you just fetched
Notice $con->query() can fail if theres a problem with the connection, the database, the table, or the query syntax itself, and $result->fetch_row() can fail if there are no results for the query. You should validate them before proceeding to the next step.
Alternatively, you can do this:
$con->query('UPDATE `servervars` SET `time` = UNIX_TIMESTAMP() WHERE ID = 1 AND UNIX_TIMESTAMP() - `time` >= 1');
if ($con->affected_rows)
{
// at least 1 second has elapsed, do stuff
}
This way we shortened your solution to a single query, that updates the field if necessary and report back that it happened or not..
I want to delete the data that expired.
I have two columns:
created_time : That contain a value indicate to time() function (ex: 1395836716).
period :That contain the period of the remain the row in database (ex: 3 or 7 or 15 or 30 per day).
I want to create a query to check on all rows in the table to know the rows that expired.
The problem is I don't know how to do that, but I tried.
$twentyFour = 60 * 60 * 24;
mysql_query("DELETE FROM content WHERE created_time + (period * $twentyFour ) > '" . time() . "' ");
But unfortunately, did not work as I expected.
Edit:
This is a result of row
Edit 2
I did it, by using php conditions:
$twentyFour = 60 * 60 * 24;
$query = mysql_query("SELECT * FROM content");
while ($data = mysql_fetch_assoc($query)) {
if ($data['created_time'] + ($data['period'] * $twentyFour) < time()) {
mysql_query("DELETE FROM content WHERE id = $data[id]");
}
}
The previous code works fine as was I want.
the problem is the previous code will occurs more server load.
I want a query to doing as the previous code does without using conditions.
DELETE FROM content
WHERE created_time < DATE_ADD(NOW(), INTERVAL `period` DAY)
May I suggest you edit your data structure and include a new column delete_time?
This delete_time should contain the UNIX timestamp of when your column should be deleted calculated from your given period.
Assuming your POST data of the period is numerical value indicating the number of days to save the data for, delete_time should be calculated by
$delete_time = time() + $_POST['period']*24*60*60;
This way, your pruning/deleting query can just be a one-liner:
mysql_query("DELETE FROM content WHERE delete_time < ".time());
That query deletes all rows whose delete_time has passed the current time().
See edit2: of the question
Given that times are held as unix timestamps this is what is required:
DELETE FROM content
WHERE (created_time + period * 60 * 60 * 24) <= NOW()
here is the: SQLFiddle
I had forgotten how much fun playing with dates and times in SQL wasn't ;-/
----------------------------------------
If using 'real' DateTime columns then this is the way to go:
Use:
DELETE FROM content
WHERE created_time < DATE_SUB(NOW(), INTERVAL `period` DAY)
or:
DELETE from content
WHERE NOW() > DATE_ADD(`created_time`, INTERVAL `period` DAY)
Dates and date differences are always difficult to get right. The issue is that you need to pick a reference point:
1) NOW() against created_at + interval,
2) NOW() against `expiry_date
3) created_at + interval against NOW()
4) expiry_date against NOW().
that while you try and work it out, you tend to switch the reference point and it is very non-intuitive.
I have created an SQL Fiddle that demonstrates all the calculations. The 'created_at' date is always midnight to 'simplify' the checking. You can change the variable called 'is_now' and see the result of all the date differences and the boolean results. It is 'interesting', maybe.
TL;DR
SQLFiddle gives the correct answer.
I need to test current time against a datetime from database, if it has been 30 mins then execute code, if not then dont. This is where I am at and I am stuck:
$link = mysqli_connect("hostname", "username", "password", "database");
$q = "SELECT id FROM dwCache ORDER BY id DESC LIMIT 1";
$qu = mysqli_query($link, $q);
while($row=mysqli_fetch_array($qu, MYSQL_ASSOC)){
$id = $row['id'];
$cache = $row['cache'];
$timest = $row['time'];
}
$newTime =
$difference = $timest
if($timest >= )
As you can see towards the bottom I lose it as I am not sure what to do.
$timest returns : 2013-02-01 12:36:01 as the format Y-m-d h-i-s
Apologies on double post, other deleted.
First convert $timest to timestamp
$time = strtotime($timest);
$curtime = time();
if(($curtime-$time) > 1800) { //1800 seconds
//do stuff
}
do it all in sql statement
SELECT id FROM `dqCache` WHERE `time`<DATE_SUB(NOW(), INTERVAL 30 MINUTE);
This will return everything from your table where the time column is before 30 minutes before now.
I like to use unix timestamps in this situation.
$timest = date('u'); // gets the unix timestamp
$q = "SELECT id
FROM `dwCache`
WHERE {$timest} - UNIX_TIMESTAMP(`timestamp_col`) > 1800";
Explanation:
This basically calculates the difference between the current time and the time in the table column. If it's higher than 1800 (30 minutes), it will select the row, and your PHP code will be executed.
Advantages
There are some advantages to using this instead of the PHP check you started doing. You will select fewer rows, thus occupy less memory.
PS:
Thumbs up for using MySQLi !
SELECT id FROM dwCache ORDER BY id DESC LIMIT 1
you'll get only id field, it's the first.
The second, for time converting: MySQL convert datetime to Unix timestamp
Third: you can convert your time string using strtotime function.
In my code, I am trying to find items in an activities table that are within the last day. This query is not returning any results, are there any problems with it? Is there a better query?
$curday = time() - (24*3600);
$query = "SELECT * FROM activities WHERE userid = '$userid' AND 'timestamp' > '$curday'";
There are two choices here, you can get and format the date through PHP or use SQL language to do it. I prefer to do it within the SQL, it also allows me to use the same query in a MySQL client.
This question is essentially the same thing: MySQL SELECT last few days?
This would be the new query:
$query = "SELECT * FROM activities WHERE userid = '$userid' AND 'timestamp' > DATE_ADD(CURDATE(), INTERVAL -1 DAY)";
you can try with unix function 'mktime' to get value of yesterday ..
as
$curday = mktime(0,0,0,date("m"),date("d")-1,date("Y"));
for reference
if your database will mysql only then you can extract yesterday in sql itself..
SELECT * FROM activities
WHERE userid = '$userid'
AND timestamp > DATE_SUB(CONCAT(CURDATE(), ' 00:00:00'), INTERVAL 1 DAY)
one more thing if timestamp is your column name don't put this column inside single quote ..
What you can use is DATE_SUB. This can be used as follows
SELECT * FROM activities
WHERE userid = '$userid'
AND timestamp > date_sub(current_date, interval 1 day)
This way you don't need to work with current date in PHP
in Informix it would be (TODAY - 1) if the column is type DATE