I know you can only have 1 timestamp per table in mysql. But I need 2. One for when an article was created and one for everytime it's updated. The latter is the one that will be changing most of the time so I decided to make that the timestamp field. For the other one, how can I prepare the time in PHP so that it looks just like a timestamp when inserted into the database:
2011-07-29 03:28:20
And if this string is prepared in PHP, will the usual ways of formatting it work, e.g.:
$time = strtotime($timestamp);
$date = date('n/d/Y # g:i a', $time);
You don't need to involve PHP in this. You can use the following pattern defaulting to NULL on the creation timestamp column, and using an ON UPDATE CURRENT_TIMESTAMP for the updated column.
CREATE TABLE test.table (
`row_inserted` TIMESTAMP NULL,
`row_updated` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
This is copied from an example on the MySQL TIMESTAMP docs.
You can use a datetime field in order to store insert time (use now() function of mysql).
Use instead a timestamp field to store update time.
create table mytb (
id int not null auto_increment primary key,
article varchar(50),
ins_time datetime,
upd_time timestamp not null default current_timestamp on update current_timestamp
) engine = myisam;
insert into mytb (
article,ins_time) values ('bla bla bla', now());
update mytb set article = 'bla bla' where id = 1
You can use MySQL function NOW() in your INSERT and UPDATE queries.
UPDATE table SET modified = NOW() WHERE id='$id'
You have two options: inside SQL using NOW():
sprintf("UPDATE table SET modified = NOW() WHERE id=%d", $id);
Or using a timestamp created in PHP:
$now = time();
sprintf("UPDATE table SET modified =%d WHERE id=%d", $now, $id);
The first is ideal if you only have one roundtrip to the database: insert all data at once.
The second allows you to carry the $now variable around for some time and re-use it. For example if you are inserting several records in a loop: you know for sure that they all have the same timestamp. Another advantage of the latter, is that time-difference between the database-server and PHP do not matter.
NOTE: I used sprintf for a minimum of security against SQL-injection. This is not, however, real and solid security. You will have to deal with cleaning data yourself trough a proper database layer.
Related
I'm creating a database for an application. The table in question will be a log of all purchases made through the app, and one of the columns in the table will store the current date & time in DATETIME() (YYYY-MM-DD HH-MM-SS format).
I know the SQL function Now() returns the current system date and time in this format, but can I create the table so that each new purchase automatically stores the current system time? I'm trying to do something like this:
CREATE TABLE purchase_log (
//bunch of code
timestamp DATETIME() NOT NULL DEFAULT Now(),
//more code
);
So that by default each entry into purchase_log will automatically store the value returned by Now(), but I don't think this is valid SQL syntax. What would be the best way to do this?
Thanks!
CREATE TABLE purchase_log (
`addedwhen` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
I used the fieldname "addedwhen" as "timestamp" is a MySQL reserved word.
Ref: https://dev.mysql.com/doc/refman/5.5/en/keywords.html
but I don't think this is valid SQL syntax.
How? It's absolutely valid; Did you actually tried running that? If not then see here http://sqlfiddle.com/#!9/e0b1a7/1
CREATE TABLE purchase_log (order_id int not null,
order_name varchar(10),
orderdate DATETIME NOT NULL DEFAULT Now()
);
insert into purchase_log(order_id, order_name) values(1,'laptop');
Add a default value to the field as CURRENT_TIMESTAMP.
However, while inserting data into the table, you will need to be careful.Either pass NULL to the field, or ensure proper timestamp.
I have set my database field to DATETIME, and when a user submits the form I want to automatically insert the current date/timestamp. How do I do this?
So far I have..
INSERT INTO expenses(user_id, amount, currency, type, description, project_id, filename)
VALUES("30","55","2","6","jult","30",DATETIME,"P")
Use NOW() instead of DATETIME on your query.
Sidenote:
Also, you will face an error on query as you are passing just 7 columns, but you are inserting 8 values.
First, you need to create a column in your database to store your datetime.
Second, rather than using "DATETIME", using gmdate("Y-m-d H:i:s") to generate a GMT/UTC datetime or date() to a local time
There's no field name in your query that I can assume is a DATETIME field, but you can use NOW(), CURRENT_TIMESTAMP, or CURRENT_TIMESTAMP().
Of course this is assuming you're using MySQL.
The easiest way would be to set a default on the row, if you can:
CREATE TABLE expenses (
/* Other row definitions */
date DATETIME DEFAULT (strftime('%s', NOW()))
);
That way you can omit the row in your insertion statement entirely.
You could use CURRENT_TIMESTAMP where you have DATETIME.
In MySQL, you cannot use a volatile function such as now() as the default for most columns. The one exception is for a timestamp column. So the create table statement could look like:
create table expenses (
. . .,
CreatedAt timestamp default current_timestamp
);
I have an html/php form that updates entries on the database server. I need to add a field to each row indicating when that entry is added, so in other words a timestamp of when the entry was created. I have been searching and found this:
http://www.createafreewebsite.net/phpmysql/alter.html
Would I do something like:
$timestamp = time();
mysql_query("ALTER TABLE notification
ADD timestamp CHAR(30) AFTER names);
mysql_query("INSERT INTO notification (`timestamp`) values ('$timestamp');
is this the correct way to approach it, and am I using the correct datatype? I would need to compare the timestamp with another timestamp generated from a javascript file later on. For example, if timestamp1 is smaller than timestamp2 than perform following functions...
Any information would be helpful, thanks!
EDIT:
Provided information as requested:
So far I have:
mysql_query("INSERT INTO notification (`program`, `month`, `day`, `year`, `sponsor`, `type`, `category`, `range`, `desc`) values ('$pName' , '$month' , '$day' , '$year' , '$sponsor' , '$type' , '$category' , '$range' , '$desc')");
time() in PHP will produce a timestamp, your MySQL table might be expecting another format, so you can just do:
mysql_query("INSERT INTO notification (`timestamp`) values (NOW());
and it will work with date and datetime fields too.
Even though your table is CHAR(30) you still have one less variable to use.
Of if you change your column data type to TIMESTAMP then you can use on update CURRENT_TIMESTAMP to fill the table cell for you.
timestamp should have a timestamp datatype. http://dev.mysql.com/doc/refman/5.0/en/datetime.html
You definitely do not want to use a column with CHAR or VARCHAR datatype to store a date or timestamp - it can make comparisons difficult later on. Also, you should consider putting a default on the timestamp column so that it is automatically populated when you insert a row, or using an insert trigger on the notification table to do the population. That way the chance of developer error is reduced.
CREATE TRIGGER notification_timestamp BEFORE INSERT
ON notification FOR EACH ROW
BEGIN
SET new.timestamp = NOW();
END;
Apologies if the syntax isn't quite right.
my simple question is .. Is it possible to insert php time() value by default in a column of a MYSQL database so that everytime i don't need to insert it. I know MYSQL provide CURR_TIMESTAMP..but they are not stored as integer unlike the time function which gives the timestamp as integer..
Any help will be greatly appreciated... Thanks
Example:
drop table if exists file_events;
create table file_events (
id int unsigned auto_increment not null,
file_id int unsigned not null,
event_time int unsigned not null default UNIX_TIMESTAMP(), # the field that defaults to "now"
primary key(id),
constraint foreign key fk_file_events_to_sam_files (file_id) references files(id) on delete cascade
) ENGINE=InnoDB;
If you want to do it on a mysql bases you can always use triggers [ http://dev.mysql.com/doc/refman/5.1/en/create-trigger.html ] just create a trigger to set the column of your choice to the current timestamp
You should just stick with the MySQL timestamp and convert it as needed. It is easy to do...
strtotime("put the mysql timestamp here");
will produce the same format (unix timestamp) as
time();
Unlike many other DBMS, MySQL doesn't support functions as default values. The only exception is the one you mention: dates accept CURRENT_TIMESTAMP (or one of their values). It appears to me that's quite an acceptable solution anyway since you can easily convert your Unix timestamp on-the-fly:
SELECT foo_id, foo_info
FROM foo
WHERE FROM_UNIXTIME(1294133369)<=foo_date
Or, from PHP:
$sql = "SELECT foo_id, foo_info
FROM foo
WHERE '" . date('Y-m-d H:i:s', 1294133369) . "')<=foo_date";
Whatever, if you absolutely need to store dates as integers, you must write your own triggers. Here's a nice example:
http://mysqldatabaseadministration.blogspot.com/2006/01/playing-with-triggers.html
Here is the table of interest when exported via phpMyAdmin:
CREATE TABLE IF NOT EXISTS `users` (
`ip` varchar(20) NOT NULL,
`lastcheck` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY `ip` (`ip`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Here is the query:
mysql_query("REPLACE INTO users SET ip = '$uip', lastcheck = '$tim'") or throwerror("part2 ".mysql_error());
$tim is set to be time();
Now for some reason lastcheck is still set as 0000-00-00 00:00:00.
Can anyone help? Thanks.
I am not sure if maybe I understand your problem, looking at column lastcheck declaration CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP that means when ever you update (ip = '$uip') this column an automatic date update will also happen lastcheck. Which mean you can write you update statment as follows :
REPLACE INTO users SET ip = '$uip';
That should also update the lastcheck field, and I think it's better to use the mysql date functions to store your date/time than writing them in php and saving them as string in the database...
try using date('Y-m-d H:i:s') in stead of time()
time() in php returns a unix timestamp and that isn't a valid insert for MyySQL datetime
hope this helps