Setting DATETIME to automatically go into database table - php

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
);

Related

How to automatically store current system time on record generation in MySQL?

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.

storing the updated timestamp whenevr the query from that particular table is called

I want to store the time at which the table was accessed/modified. I know how to put current timestamp.
But what we must do to store the updated timestamp ?
I am not sure what exactly you are looking for but below query might be helpful.
you can create/upate your table to have "On Update Current_timestamp"
CREATE TABLE t1 (
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
To update a timestamp when accessing a record you could use a stored procedure to select the records and then update the timestamp fields.
#Suresh Kamrushi has suggested a solution for updating the timestamp when the record is modified.

php mysql timestamp works only on update

i am using a timestamp type column in my mysql database, and i have enabled the option for auto update timestamp, but the time stamp works only on update command and not on insert
i am using navicat mysql client
Thanks in advance.
Try assigning the current timestamp as the default value along with enabling auto-update. That should work for you.
See: current_timestamp
Did you mean something like this..
To set the TIMESTAMP column in either table to the current timestamp at insert time, explicitly assign it that value.
INSERT INTO t1 VALUES (NOW());
INSERT INTO t2 VALUES (CURRENT_TIMESTAMP);
http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html
Set the column default value to CURRENT_TIMESTAMP.
If you are using a server side language to insert data into the table, you could simply insert the current date into that column. In PHP, for example, that would be
<?php
$time = time();
?>

Adding Timestamp to Database Table

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.

How to simulate 2 timestamp fields in a MySQL table?

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.

Categories