Adding Timestamp to Database Table - php

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.

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.

Setting DATETIME to automatically go into database table

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

MYSQL ON UPDATE CURRENT_TIMESTAMP not updating when using INSERT OR REPLACE?

I unable to update current time(NOW) in last_updated cloumn.
Because i have read this query from text file.
INSERT OR REPLACE INTO table_name (kb_corporate_guid,kb_user_guid,
name,last_updated)
VALUES ('100','121','FAQ','2013-02-07 07:06:05');
I want to ignore last_updated cloumn value '2013-02-07 07:06:05' even if i specified in query and replace with NOW() value into last_updated cloumn.
I tried this one but it won't work for me.
ALTER TABLE table_name
CHANGE `last_updated` `last_updated` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP;
Option 1
You may create trigger on insert/update which will update last_updated field with MySql NOW() function, it will overwrite the field value, but it might slow down the process when you do bulk insert/update.
Option 2
Find and Replace the text for last_updated field and timestamp values from text file.
Option 3
Create temporary table with same schema and import into temporary table then use INSERT INTO main_table SELECT corp_id, user_id, name, NOW() FROM temp_table table to insert into main table.
Default is used when the value is not sent in the query, use now in the query instead of timestamp..

Unique Identifier Mixed Format with Date Prefix (Php / MySQL)

I am creating a ticketing system that will keep track of tickets that a customer creates. The ticket's basic information will be stored in a table 'tickets' who's structure is as follows:
Primary Key (int 255)
Ticket_Key (varchar)
Ticket Number (varchar 500)
Label
Date Created
Delete
and so on..
The issue is that there will eventually be a large amount of tickets and we need a more uniform way of identifying tickets. I would like PHP to create a Ticket Number in the ticket number that will contain mixed values. The date (in format 20111107), followed by a auto incremented value 1001. 1002, 1003, ...). So the Ticket Number will be 201111071001 for an example.
The issue is how do I program this in PHP to insert to the MySQL database? Also, how do I prevent the possibility of duplicate values in the Unique Id in PHP? There will be a very large amount of customers using the table to insert records.
What about using an auto-increment and combining this with the date field to generate a sequence number for that date and hence a ticketId.
So your insert process would be something like this:
INSERT INTO table (...ticket info...)
You would then retrieve the auto-increment for this row and run a query like this
UPDATE table SET sequence = (SELECT ($id-MAX(auto_increment)) FROM table WHERE date_created=DATE_SUB(CURDATE(),INTERVAL 1 DAY)) WHERE auto_increment=$id
You could then easily create a ticketId of format YYYMMDDXXXX. Assuming you never retro-add tickets in the past this would only ever require these two queries even under heavy usage.
[EDIT] Actually, after looking into this there is a much better way to do this natively in MySQL. If you define two columns (date and sequence) and make them a primary key (both columns) with the sequence field as an auto-increment then MySQL will update the sequence column as an auto-increment per date (i.e. it will start with value 1 for each date).
[EDIT] A table structure along these lines would do the job for you:
CREATE TABLE IF NOT EXISTS `table` (
`created_date` date NOT NULL,
`ticket_sequence` int(11) NOT NULL auto_increment,
`label` varchar(100) NOT NULL,
[other fields as required]
PRIMARY KEY (`created_date`,`ticket_sequence`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
When retrieving the data you could then do something like
SELECT CONCAT( DATE_FORMAT(created_date,'%Y%m%d'),LPAD(ticket_sequence,4,'0')) AS ticket_number, other fields.... FROM table
as i understand that you want to make one result of two different fields like datefield and ticketnumfield
in mysql you do this through the command:
SELECT concat( datefield, ticketnumfeild ) FROM `tbl_name`
this query return the result like 201111071001
I did something like this before where I wanted to refresh the counter for each new day. Unfortunately I do not speak PHP so you will have to settle for explanation and maybe some pseudo code.
Firstly, create a couple of fields in a config file to keep track of your counter. This should be a date field and a number fields...
LastCount (Number)
LastCountDate (Date)
Then you make sure that your ticket number field in your database table is set to only unique values, so it throws an error if you try to insert a duplicate.
Then in your code, you load your counter values (LastCount and LastCountDate) and you process them like so...
newCount = LastCount;
if LastCountDate == Today
increment newCount (newCount++)
else
reset newCount (newCount = 1)
you can then use newCount to create your ticket number.
Next, when you try to insert a row, if it is successful, then great. If it fails, then you need to increment newCount again, then try the insert again. Repeat this until the insert is successful (put it in a loop)
Once you have successfully inserted the row, you need to update the database with the Count Values you just used to generate the ticket number - so they are ready for use the next time.
Hope that helps in some way.

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