I'm playing with wordpress $wpdb function.
First of all, I want to create a database table with a column corresponding to the time, so that I can save user actions into this table and know when they did it.
Creating a table:
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id INT NOT NULL AUTO_INCREMENT,
actiontime NOT NULL DATETIME,
PRIMARY KEY (id)
) $charset_collSate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
// execute the query
dbDelta( $sql );
Is this correct? Will it create a DATETIME field that I'm after? I would want a time stamp such that I can get the difference on minute/second intervals.
Inserting in such table:
$wpdb->insert($table_name, array(
'actiontime' => now()
));
Will this work?
I can't check it manually, because I'm developing on a side machine and only have ftp access to live-server and notepad. I can't test anything locally.
I use this php function to get the current value for a MySQL DATETIME field.
/**
* Return current date time.
*
* #return string ISO date time (Y-m-d H:i:s)
*/
function now()
{
return date('Y-m-d H:i:s');
}
There are a few options you could consider,
If you're using plain old PHP and MySQL, you can use the SQL now() function to insert data into a timestamp field like this,
INSERT INTO projects (actiontime) VALUES (now())
Another options would be to use a PHP variable such as, $timestamp = date('Y-m-d G:i:s'); and inserting it in a SQL query:
$timestamp = date('Y-m-d G:i:s');
INSERT INTO projects (actiontime) VALUES ($timestamp);
Hope it helps!
try PHP time() for epoch timestamp
Related
I have an upload script written in PHP which takes care of data from CSVs and inserts it into each specific table for each CSV that is uploaded.
I need to fix an issue with it not inserting data from a different date format correctly. It needs to cover all date formats and save it like YYYY-MM-DD (2016-09-27), except time.
It looks like this:
Database table:
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USER VARCHAR(50) NOT NULL,
Date DATE,
Time TIME
PHP/MySQL
$stmt = $conn->prepare("INSERT INTO ".$table_name." (User, Date,Time) VALUES (?,?,?)");
$stmt->bind_param("sss", $user, $date,$time);
$user = $data_array[$i][0];
$date = $data_array[$i][1];
$time = $data_array[$i][2];
$stmt->execute();
I've been reading about STR_TO_DATE but I'm not sure where I should use it in this case.
At first i noticed your define the vars after u use them with bind_param()
$user $date $time
Like this:
$user = $data_array[$i][0];
$date = $data_array[$i][1];
$time = $data_array[$i][2];
$stmt->bind_param("sss", $user, $date,$time);
Next:
You can use MySQL Date Format functions.
See: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
With this function you can convert your string date into a valid MySQL date.
VALUES(?,DATE_FORMAT('?','format'),?)
Replace format with the format the data is in
Example from Manual: SELECT DATE_FORMAT('2009-10-04 22:23:00', '%W %M %Y');
I don't want to update my timestamp field when update. I need to keep previous datetime in that field. But its updating automatically even I tried following
$data = array(
'start_time' => $start,//previous datetime
'user_id' => $agent_id,
....
);
$this->db->where('id', $chat_id)->update('chat_state', $data );
When I leave $start or force with previous datetime. Not work in both cases. Its updating with CURRENT TIMESTAMP in both cases
whats wrong here??
Connect to your mysql server using MySQL Workbench, to check your table's schema, by running the following queries:
USE mydatabase;
SHOW CREATE TABLE mytable;
I bet you'll see something like ON UPDATE CURRENT_TIMESTAMP associated with your start_time field.
Note that, relying on DBMS to auto-update values is not a good practice; It gives you surprises, and you end up spending hours to figure out the issue.
Let's remove the "ON UPDATE CURRENT_TIMESTAMP" clause, like this:
ALTER TABLE mytable MODIFY start_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
This should solve the problem.
Read more about TIMESTAMP's behaviors in different situations.
Follow these steps
Select exist value (start_time)
Update exist value to new field
insert new value
01 Select current value in db
$query = $this->db->query("SELECT start_time FROM chat_state WHERE user_id = $chat_id");
$result = $query->result_array();
02 Update exist value
$data = array(
'old_time' => $result[0]['start_time'] // move start_time to new field
);
$this->db->where('id', $chat_id)->update('chat_state', $data );
03 insert new value
$data = array(
'start_time' => date('Y-m-d H:i:s'), // new Time stamp
'user_id' => $agent_id
);
$this->db->where('id', $chat_id)->update('chat_state', $data );
Probably you have the column type as DATETIME; you need to change the type to TIMESTAMP and default null. It will not be updated automatically.
Then, while inserting the data
'start_time'=>date("Y-m-d H:i:s")
And when you want to print it in view
date('d-M-y', strtotime($record['start_time']));
I need update all rows in my events table. There is column event_date with timestamp datatype.
But if i update each row (event_date column) with new date (expample: 2015-12-12 12:00:00) then i have some rows with value 2015-12-12 13:00:00.
Point is - why are some rows correct and some are +1h?
In PHP i am using Nette framework and his DateTime object which extends standart PHP DateTime...
Any ideas, hints why this happends?
EDIT: query looks like this:
UPDATE `events`
SET `event_date`='2016-2-13 12:00:00', `event_date_to`=NULL
WHERE (`id` = 203)
Values in php i am setting like this:
$row->event_date = date("Y-m-d H:i:s", $oldRow['event_date']);
Problem starts sooner - in this table was dates like 2016-2-13 00:00:00 but after select and echo dates changed to 2016-2-12 23:00:00 - but no all rows... only someones. So i make select:
select events.id, events.event_date, events.event_date_to,
concat(year(event_date), '-', month(event_date), '-',
day(event_date), ' 12:00:00') as new_event_date,
IF(events.event_date_to IS NULL,null, concat(year(event_date_to),
'-', month(event_date_to), '-', day(event_date_to), ' 12:00:00')) as
new_event_date_to from events
That select give me rows like this:
769,2014-04-22 19:30:00,2014-04-22 21:45:00,2014-4-22 12:00:00,2014-4-22 12:00:00
It means: id, event_date(real db value), event_date_to(real db value), event_date(new value for insert), event_date_to(new value for insert - can be NULL)
And saved to csv file... This file i am parsing now and in foreach updating each row...
I checked ALL queries and times are OK (12:00:00) so i don't understand and stuck :)
Your MySQL timezone is probably dissimilar to that of your code (specified in php.ini).
To test this, try inserting this value into a DATETIME or TIMESTAMP column:
foo_column = NOW()
Concurrently, insert $datetime into a separate column - lets say $datetime simply equals the current time: date('Y-m-d H:i:s', time())
bar_column = '$datetime'
If the values are different - then there you have it. Your database is essentially interpreting time differently to your php.
I'm having trouble inserting a record with a date field. No matter what I do, the date field gets stored as '0000-00-00'. The value comes into the php script as a string in this format:
'9/13/2013'. I'm converting to a date using strtotime, then trying to insert the record. Here's the code. Why can't I get this to work? Thanks!
$my_date = strtotime($_POST['d']);
//die(date("Y-m-d", $my_date)); //<--outputs just fine if I uncomment this
$sql = "INSERT INTO locations (id, my_date) VALUES ('$id', '$my_date')";
$result = mysql_query($sql);
I'm converting to a date using strtotime
strtotime returns a unix timestamp (integer), not a date string. You can format it for MySQL before inserting with the date function:
$my_date = date('Y-m-d H:i:s', strtotime($_POST['d']));
Alternatively, you can use the DateTime class for this purpose.
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");