Correct Date and Time Columns in MySQL - php

I have a timezone mismatch I need to correct in a table. All dates and times before unix timestamp 1253568477 need to have 5 hours added to their values to make them equal GMT.
I have the following columns...
date (data type date), off by -5 hours
time (data type time), off by -5 hours
timestamp (data type int), this column is the correct time
The reason the timezones are off is because of the way I was setting the values when inserting the rows...
$sql = "insert into email_opens (userid, email, serial, date, time, timestamp) values (
'$userid',
'$opened_by',
'$serial_number',
now(),
now()',
'".gmmktime()."'
)";
The now() value was using the server timezone (eastern) whereas the gmmktime value specified GMT. I have since corrected this query to always use GMT.
Is there a way I can add 5 hours to both time and date columns for those rows where timestamp < 1253568477 in one batch query?
Clarification:
My goal is to update each incorrect row in the table with the correct time by adding 5 hours to each value.

Try with this:
UPDATE mail_opens SET date = DATE_ADD(CONCAT(date, ' ', time), INTERVAL 5 HOUR), time = DATE_ADD(CONCAT(date, ' ', time), INTERVAL 5 HOUR);
And then you probably need this:
<?php
echo date('Y-m-d H:i:s')."<br>";
$addhours = strtotime('+5 hour');
echo $addhours."<br>";
$newdate = date('Y-m-d H:i:s', $addhours);
echo $newdate;
?>
So, using that:
<?php
$addhours = strtotime('+5 hour');
$newdate = date('Y-m-d H:i:s', $addhours);
$sql = "insert into email_opens (userid, email, serial, date, time, timestamp) values (
'$userid',
'$opened_by',
'$serial_number',
'$newdate',
'$newdate',
'".gmmktime()."'
)";
?>

sure, work out the time you corrected the problem so you know only to update records that have a value less than the unix timestamp of your timezone change.
Then update the field and add 60 * 60 * 5 (5 hours in seconds) to those records.
So, your query would be the following:
UPDATE email_opens SET timestamp = (timestamp + 18000) WHERE timestamp < 1253568477;
Cool.

Related

How to insert the current date to database then retrieve it?

$query = mysql_query ('insert into pm timestamp values("'.strtotime("now").'")')
echo "<td>".date('d-M-Y H:i:s', $date3)."</td>
timestamp in database is INT(11)
I am able to get today date but I can't get the current time.
please help thank you !
You have to get the timestamp directly in your database with MySql and not with PHP. Change the type of your "timestamp" to timestamp and use the appropriate function "NOW()"
Your request would be like that : INSERT INTO table (timestamp) VALUES 'NOW()'
time();
Gives you current date and time in unix format - timestamp
$query = mysql_query ('insert into pm timestamp values("'.time().'")')
and after that when you retreive field value to var $date3 just echo it like you did
echo "<td>".date('d-M-Y H:i:s', $date3)."</td>";
If you want timestamp, use time()
php > echo time();
1406880195

php mysql last visit

I have website where the user can show his last visit to the website every time he logs in.
the type of last_activity column in the database is 'time'.
I made a code that shows the current date and save it in a variable $currentDate
and then set variable $currentDate into last_activity column in the database and update the column every time the user logs in.
but when I test the code I get this result:
your last visit: 00:00:00
the type of last_activity column in the database is 'time'.
here is my code:
<?php
session_start();
include('db.php');
date_default_timezone_set('Asia/Riyadh');
$currentDate = date('m/d/Y h:i:s a', time());
if(isset($_SESSION['Email']) === true)
{
mysql_query("UPDATE `table` SET `lastactivity` = ".$currentDate." WHERE email = '".$_SESSION['Email']."'");
$query = "SELECT * FROM `table` WHERE email = '".$_SESSION['Email']."'";
$run = mysql_query($query);
while($row = mysql_fetch_array($run))
{
$name = $row[1];
$active = $row[10];
echo 'welcome '.$name;
echo 'your last visit '.$active;
;
You should use the type DATETIME or TIMESTAMP to store a datetime value instead of TIME. The TIME datatype has no notion of dates:
The TIME Type
MySQL retrieves and displays TIME values in 'HH:MM:SS' format (or
'HHH:MM:SS' format for large hours values). TIME values may range from
'-838:59:59' to '838:59:59'.
...
Invalid TIME values are converted to '00:00:00'.
Because of that you get
your last visit: 00:00:00
back from the database as your output.
The DATE, DATETIME, and TIMESTAMP Types
The DATETIME type is used for values that contain both date and time
parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD
HH:MM:SS' format. The supported range is '1000-01-01 00:00:00' to
'9999-12-31 23:59:59'.
Edit:
TIMESTAMP and in newer MySQL versions DATETIME columns have nice features, i.e. automatic update:
Automatic Initialization and Updating for TIMESTAMP and DATETIME
As of MySQL 5.6.5, TIMESTAMP and DATETIME columns can be automatically
initializated and updated to the current date and time (that is, the
current timestamp). Before 5.6.5, this is true only for TIMESTAMP, and
for at most one TIMESTAMP column per table.
Edit 2:
Furthermore produces
$currentDate = date('m/d/Y h:i:s a', time());
no valid format of an DATETIME literal. You could use STR_TO_DATE() to convert your value to DATETIME, but I wouldn't recommend this. Better you change your UPDATE statement using the MySQL function NOW() to:
mysql_query("UPDATE `table` SET `lastactivity` = NOW() WHERE email = '".$_SESSION['Email']."'");
You can format your DATETIME value, while retrieving it from MySQL with DATE_FORMAT() and give this computed column a name:
$query = "SELECT *, DATE_FORMAT(lastactivity, '%m/%d/%Y %h:%i%s %p') as last_activity FROM `table` WHERE email = '".$_SESSION['Email']."'";
$run = mysql_query($query);
while($row = mysql_fetch_array($run))
{
$name = $row[1];
$active = $row["last_activity"]; // access to the column by column name
// ...
Note
I recommend to switch from the deprecated mysql_* functions to PDO or mysqli with prepared statements and placeholders instead of concatenation of an sql statement.

PHP/MySQL Deleting before interval

so I want my MySQL Row to delete when it's been 2 hours after being added by said user.
Here's what I have;
$Link = MySQL_Connect // etc
$now = date('Y-m-d H:i:s', time())
$query = "DELETE FROM my_table WHERE time < NOW() - INTERVAL 2 HOUR";
$result = mysql_query($query) or die ('unable to run: ' .mysql_error());
But when I run it, it's deleting every row even if it hasn't been 2 hours.
Incase this helps, My insert query;
$now = date('Y-m-d H:i:s', time());
mysql_query ("INSERT INTO my_table (name, email, time) values ('$Name', '$Email','$now')");
echo 'Proceed';
Try this:
$query = "DELETE FROM my_table WHERE DATE_ADD(`time`, INTERVAL 2 HOUR) < NOW()";
It adds two hours to your column value and if it is less then the current time it will be deleted.
SQL Fiddle
Are your MySQL server and your HTTPD the same machine (I know mine aren't)? 'cause you're inserting your MySQL data with times from the PHP server and then comparing with MySQL times...
Might be better to insert like this:
INSERT INTO my_table(name,email,time) VALUES ('$name','$email',NOW())
at least that will ensure comparing the right times...
And also make sure TIME is defined as a DATETIME, not just a DATE

Count number of logins per day in PHP Timeclock (PHP Mysql)

What are the mysql codes to count the number of logins per day in PHP Timeclock?
timestamp bigint(14) is used and I have no idea how to separate them by date.
How do I count the number of ROWS per day?
Here's the command to create the table info:
CREATE TABLE info (
fullname varchar(50) NOT NULL default '',
`inout` varchar(50) NOT NULL default '',
timestamp bigint(14) default NULL,
KEY fullname (fullname)
) ENGINE=MyISAM;
Sorry I'm just a newbie trying to understand php and MySQL.
Anyway, I can add either of the two in info table:
timestamp timestamp default NULL,
or logindate date default NULL,
Suppose I have this portion of the code saved in a php file, how can I modify it so date or timestamp is inserted in info table everytime a user logs in?
$time = time();
$hour = gmdate('H',$time);
$min = gmdate('i',$time);
$sec = gmdate('s',$time);
$month = gmdate('m',$time);
$day = gmdate('d',$time);
$year = gmdate('Y',$time);
$tz_stamp = mktime ($hour, $min, $sec, $month, $day, $year);
if (strtolower($ip_logging) == "yes") {
$query = "insert into ".$db_prefix."info (fullname, `inout`, timestamp, notes, ipaddress) values ('".$fullname."', '".$inout."',
'".$tz_stamp."', '".$notes."', '".$connecting_ip."')";
} else {
$query = "insert into ".$db_prefix."info (fullname, `inout`, timestamp, notes) values ('".$fullname."', '".$inout."', '".$tz_stamp."',
'".$notes."')";
}
$result = mysql_query($query);
Since it's a BIGINT (why, btw?) I assume it's a UNIX Timestamp.
I haven't tested this, but something along the lines of this should work:
SELECT DATE(FROM_UNIXTIME(timestamp)) AS date, COUNT(*)
FROM info
GROUP BY date
You might wanna just store the timestamp as a TIMESTAMP column type, and then just use DATE(timestamp) to group by date.
Add a column of date only (without the time) and use this:
SELECT COUNT(*), dateColumn FROM info WHERE fullname='{The user full name}' GROUP BY dateColumn

Store php datetime in mysql database

I can't believe I can't do this, but I want to be able to store the current date and time from php in to a mysql table.
The column in the table is type datetime.
I've tried this
$current_date = date("Y-m-d");
$my_date = strtotime($current_date);
INSERT INTO my_table (date_time) VALUES ('$my_date')
but my timestamp comes up as 0000-00-00 00:00:00
This must be so easy to do but I just can't get it working!
I want to use the timestamp from php rather than using the mysql now() function
Try this:
$my_date = date("Y-m-d H:i:s");
INSERT INTO my_table (date_time) VALUES ('$my_date');
In the date-format parameter of the date function, use :
'H' for 24hr format
'h' for 12hr format
Don't save it as the Unix Timestamp (which strtotime() outputs), but as "2012-12-02 13:00" into the DATETIME column.
Create column type TIMESTAMP and set it to NOT NULL. Then pass in NULL during INSERT and MySQL will insert current date and time. This works for me.
set the 'type' of column named 'date_time' as 'DATETIME' and run the following query:
INSERT INTO my_table (`date_time`) VALUES (CURRENT_TIMESTAMP)
If you have the date in PHP as a timestamp, you can use the FROM_UNIXTIME function [1]
mysql> insert into table_name values (FROM_UNIXTIME(your_timestamp_here));
Hope it helped
[1]. https://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_from-unixtime
Remove the strtotime()
$current_date = date("Y-m-d");
INSERT INTO my_table (date_time) VALUES ('$current_date')
If you want to include the hour, minutes and seconds,
$current_date = date("Y-m-d H:i:s");

Categories