I have DATETIME value in my database which is CURRENT_TIMESTAMP by default, and this column can be empty. When I try creating objects in PHP and inserting it into the database, it still asks me to insert that DATETIME value.
My question is: how can I insert object into database without defining that DATETIME value? Shouldn't the database enter this value automatically?
When I am updating that object, I don't want to enter that value at all.
You could use DEFAULT keyword or do not specify that column at all:
CREATE TABLE myTab(i INT PRIMARY KEY AUTO_INCREMENT,
b TEXT,
c TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
INSERT INTO myTab(b, c)VALUES ('a', DEFAULT);
INSERT INTO myTab(b) VALUES ('b');
SELECT * FROM myTab;
Rextester Demo
Related
I have an admin users db, I want to create a column with type datetime for edits, to know when and admin acc was edited, I will introduce the time with php and MySQLi, im on phpmyadmin, when I try to create the column it says:
#1292 - Incorrect datetime value: '0000-00-00 00:00:00' for column 'editado' at row 1
MySQL code is:
ALTER TABLE `admins` ADD `editado` DATETIME NOT NULL AFTER `password`;
Tried to execute on SQL but nothing, how can I do this?
If the table is not empty when you add a column, you need to first add the column as NULLABLE, update all the records in the table assigning a value to the column, then you can change the column you added from NULLABLE to NOT NULL. So something like this should be done:
ALTER TABLE admins ADD editado DATETIME NULL AFTER password;
UPDATE admins SET editado = '1900-01-01 00:00:00';
ALTER TABLE admins MODIFY editado DATETIME NOT NULL;
Not sure if the last query is correct syntax as I don't write MySQL often but thats what should happen.
i have table called post_data having username,email,pass,cam_name,upd_date(of type datatime) fields in that. but the problem is when i insert username, email pass into the table that upd_date(datatime) is updated with current data and time. how can i restrict that ...
I even change the datatype form DATETIME to TIMESTAMP
No use..still it stores current date and time when i update only certain columns.
can any tell me ...
You have set the default datetime for that column. You need to alter the column.
alter table post_data alter column upd_date drop default;
If your column doesn't accept NULL, then it will implicitly set default value. You need to alter you table to allow null.
Data Type Default Values
If a column definition includes no explicit DEFAULT value, MySQL
determines the default value
ALTER TABLE post_data MODIFY upd_date datetime null;
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.
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
This seems like a really simple one but I'm struggling to figure it out. I want a column in my database that lists when a record was first created and another column that says when it was updated. It's my understanding I should be able to do all this just using MySQL. All help is appreciated :)
This stinks still no answer, reasons I'm already starting to miss Ruby on Rails...
You will probably need to use a combination of the Datetime datatype and the Timestamp data type. I would set my created column as a DateTime with a DEFAULT NOW(), and my updated column as a Timestamp with DEFAULT CURRENT_TIMESTAMP and an ON UPDATE CURRENT_TIMESTAMP attribute.
Here are the docs for the Timestamp dt:
http://dev.mysql.com/doc/refman/5.0/en/timestamp.html
In a CREATE TABLE statement, the first TIMESTAMP column can be declared in any of the following ways:
With both DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP clauses, the column has the current timestamp for its default value, and is automatically updated.
With neither DEFAULT nor ON UPDATE clauses, it is the same as DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP.
With a DEFAULT CURRENT_TIMESTAMP clause and no ON UPDATE clause, the column has the current timestamp for its default value but is not automatically updated.
With no DEFAULT clause and with an ON UPDATE CURRENT_TIMESTAMP clause, the column has a default of 0 and is automatically updated.
With a constant DEFAULT value, the column has the given default and is not automatically initialized to the current timestamp. If the column also has an ON UPDATE CURRENT_TIMESTAMP clause, it is automatically updated; otherwise, it has a constant default and is not automatically updated.
To fulfill your question and for others viewing this question, here is the answer. Note this was written for MySQL 5.x.
DROP TABLE IF EXISTS `test1`;
CREATE TABLE `test1` (
`id` INT NULL AUTO_INCREMENT ,
`name` varchar(50) NOT NULL ,
`created` DATETIME ,
`updated` DATETIME ,
PRIMARY KEY (`id`),
INDEX (`name`)
);
DELIMITER $$
DROP TRIGGER IF EXISTS `test1_created`$$
CREATE TRIGGER `test1_created` BEFORE INSERT ON `test1`
FOR EACH ROW BEGIN
SET NEW.`created` = UTC_TIMESTAMP();
SET NEW.`updated` = UTC_TIMESTAMP();
END;
$$
DROP TRIGGER IF EXISTS `test1_updated`$$
CREATE TRIGGER `test1_updated` BEFORE UPDATE ON `test1`
FOR EACH ROW BEGIN
SET NEW.`updated` = UTC_TIMESTAMP();
END;
$$
DELIMITER ;
Note
You could use TIMESTAMP for the updated column which would have automatically updated the value thus not requiring the BEFORE UPDATE trigger, however TIMESTAMP has a range from 1970 to 2038 which is fast approaching and I like to think my applications will live forever :). Although TIMESTAMP is only 4bytes while DATETIME is 8bytes.
TIMESTAMP range '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC
DATETIME range '1000-01-01 00:00:00' to '9999-12-31 23:59:59'
From the MySQL 5.0 Certification Guide:
CREATE TABLE ts_test5 (
created TIMESTAMP DEFAULT 0,
updated TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
data CHAR(30)
);
To control the initialization and update behaviour of a TIMESTAMP column, you add either or both of the DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP attributes to the column defintion when creating the table with CREATE TABLE...
and
...if you do not specify either of the DEFAULT CURRENT_TIMESTAMP or ON UPDATE CURRENT_TIMESTAMP attributes when creating a table, MySQL automatically assigns BOTH to the first TIMESTAMP column
Also
you cannot use DEFAULT CURRENT_TIMESTAMP with one column and ON UPDATE CURRENT_TIMESTAMP with another
If you can't use the timestamp fields with default attributes that Paul W has suggested, you can use AFTER INSERT and AFTER UPDATE triggers to populate the fields.
You will need two fields "Created" and
"Updated" with type datetime. When a
new entry is inserted then insert
"Created" with current time stamp.
When a update is happening insert
"Updated" with the current time stamp,
and let the "Created" field remain as
it is.
For current time stamp you can use
NOW() in your mysql query.