I'm having a bit of a tricky issue here. My database queries are inaccurate because the NOW() function appears to have the wrong timezone.
First off, after connecting to the database, I set the appropriate timezone using the following code:
ini_set('date.timezone', 'America/Toronto');
mysql_connect('localhost', 'myusername', 'mypassword') or die(mysql_error());
mysql_select_db('mydatabase') or die(mysql_error());
mysql_query("SET SESSION time_zone = 'America/Toronto'");
As you can see, I've also set the timezone via PHP as well.
The problem is that I am running the following script, and despite the fact that it is 12:24am now, it is outputting the SUM()'s for yesterday.
Here is the code I am using:
$sql = mysql_query("select
website,
sum(case when date_format(from_unixtime(`date_assigned`), '%Y-%m-%d') = date_format(now(), '%Y-%m-%d') then 1 else 0 end) AS c_today
from `assignments`
group by website
order by website asc
") or die(mysql_error());
As I mentioned, c_today
is giving me the SUM()'s of yesterday right now. It is causing major issues because the counts seem to be off everywhere.
What is going on here and why isn't it working properly?
I have tried using the following code within this script:
echo '<p>Current server time is: '.date('F j Y, g:ia', time()).'<br />';
echo 'Current database time is: '.date('F j Y, g:ia', mysql_result(mysql_query("select unix_timestamp(now())"), 0)).'</p>';
This echo's:
Current server time is: September 10 2014, 12:28am
Current database time is: September 10 2014, 12:28am
Any help would be greatly appreciated.
EDIT:
I have made some progress.
I have added the following to the script:
echo mysql_result(mysql_query("select timediff(now(),convert_tz(now(),@@session.time_zone,'+00:00'));"), 0);
This is echoing -07:00:00
, meaning it is off by 2 hours. Why would it be off by 2 hours if I have explicitly used the following code after the connection?
mysql_query("SET SESSION time_zone = 'America/Toronto'");
This should make it -05:00:00
, not -07:00:00
.
EDIT 2:
It appears using the SET SESSION time_zone
query entirely has no effect on actually setting the sessions timezone.