I've a table folio with timestamp set to auto update.
CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
PDO statement in PHP is not causing the timestamp to update.
$statement = $this->connection->prepare("
INSERT INTO folio(publication, productId)
VALUES(:publication, :productId)
ON DUPLICATE KEY UPDATE
id=LAST_INSERT_ID(id), publication=:publication, productId=:productId");
following manual approach works but is not desirable.
$statement = $this->connection->prepare(
"INSERT INTO folio(publication, productId)
VALUES(:publication, :productId)
ON DUPLICATE KEY UPDATE
id=LAST_INSERT_ID(id), publication=:publication, productId=:productId, timestamp=NOW()");
Update: Here's my folio table structure
CREATE TABLE `folio` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`publication` varchar(255) DEFAULT NULL,
`productId` varchar(255) DEFAULT NULL,
`timestamp` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_folio` (`publication`,`productId`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;
Update 2: Table structure after setting timestamp to not null
CREATE TABLE `folio` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`publication` varchar(255) DEFAULT NULL,
`productId` varchar(255) DEFAULT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_folio` (`publication`,`productId`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
As far as I can see, the problem with your queries might be because you made timestamp field nullable
`timestamp` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
Try making it NOT NULL - since you have valid default value for it, MySQL won't complain you have not provided the value in the query:
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
Also, try renaming timestamp field to something more sane, e.g.:
`changed_timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
Also, as mentioned in my comments - you don't need to provide all fields in ON DUPLICATE KEY section, but only data fields:
INSERT INTO folio(publication, productId)
VALUES(:publication, :productId)
ON DUPLICATE KEY UPDATE
publication=:publication,
productId=:productId
It is because if MySQL detects you have a duplicate key condition, it won't insert new row, but update the existing one, therefore id column must be left intact.
UPDATE
Seems that not updating the timestamp column is a documented behavior - MySQL manual for TIMESTAMP columns
Citing the needed paragraph:
If the column is auto-updated, it is automatically updated to the current timestamp when the value of any other column in the row is changed from its current value. The column remains unchanged if all other columns are set to their current values. To prevent the column from updating when other columns change, explicitly set it to its current value. To update the column even when other columns do not change, explicitly set it to the value it should have (for example, set it to CURRENT_TIMESTAMP).
So, you are meeting all conditions :) - when you insert the record the timestamp should be populated correctly.
But when you provide the duplicate values on order to update the timestamp, MySQL sees you set the values that already exist in the row (otherwise it wouldn't be duplicate), therefore it does not update the timestamp column.
So, the solution is straightforward and already found by you - update the timestamp column explicitly whenever you provide the duplicate values, e.g.:
INSERT INTO folio(publication, productId)
VALUES(:publication, :productId)
ON DUPLICATE KEY UPDATE
`timestamp` = NOW()
Anyway, making timestamp NOT NULL won't hurt.
If the new INSERT values are the same as the old values in the duplicate row then apparently MySQL does not perform the UPDATE, therefore the ON UPDATE CURRENT_TIMESTAMP is not fired. :(
So, as an awkward workaround, you can add a dummy field to your table, forcing the UPDATE to occur (in the case of a duplicate id):
$statement = $this->connection->prepare("
INSERT INTO folio(publication, productId)
VALUES(:publication, :productId)
ON DUPLICATE KEY UPDATE
id=LAST_INSERT_ID(id), publication=:publication, productId=:productId,
dummy = NOT dummy
");
...as suggested in the User Comments here: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
it's just
insert into your_table (a, b) values (?, ?) on duplicate key update created = current_timestamp
For better or worse, MySQL does not , in any way, default-update timestamps in the case of insert-uniquely type calls.
it does not matter which of the three, insert-on-dupe, replace, insert-ignore you are using
it does not make any difference whatsoever which settings or qualities you use on the fields, table or anything else
It just has to be done manually by adding created = current_timestamp on the end.
Unfortunately that's it!
Related
CREATE TABLE IF NOT EXISTS `$id` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`start` varchar(10) NOT NULL,
`end` varchar(10) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=45 ;
INSERT INTO `$id`(`start`, `end`) VALUES ('0','0')
I have been trying to figure out how I can bind these two Mysql(requests(?)) into one with no success. Basically I want it to work so when I create the table it should also add the values 0 and 0 to "start" and "end" rows. But I still want the "Create table if not exists" to be in effect for the INSERT INTO. So if the table exist don't INSERT either.
You could do that with following single statement:
CREATE TABLE IF NOT EXISTS `$id` (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`start` VARCHAR(10) NOT NULL,
`end` VARCHAR(10) NOT NULL,
`date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB
SELECT '0' AS `start`, '0' AS `end`;
You use the CREATE TABLE ... SELECT syntax with selecting not from a table, but constant values and get the autoincrement value and the current_timestamp by default.
as of MySQL 5.5.6 or newer, see following excerpt from the manual, CREATE TABLE ... SELECT:
As of MySQL 5.5.6, handling of CREATE TABLE IF NOT EXISTS ... SELECT
statements was changed for the case that the destination table already
exists. This change also involves a change in MySQL 5.1 beginning with
5.1.51.
Previously, for CREATE TABLE IF NOT EXISTS ... SELECT, MySQL produced
a warning that the table exists, but inserted the rows and wrote the
statement to the binary log anyway. By contrast, CREATE TABLE ...
SELECT (without IF NOT EXISTS) failed with an error, but MySQL
inserted no rows and did not write the statement to the binary log.
MySQL now handles both statements the same way when the destination
table exists, in that neither statement inserts rows or is written to
the binary log. The difference between them is that MySQL produces a
warning when IF NOT EXISTS is present and an error when it is not.
This change means that, for the preceding example, the CREATE TABLE IF
NOT EXISTS ... SELECT statement inserts nothing into the destination
table as of MySQL 5.5.6.
I am working on a function that compares the date created and date modified of images and return the status of each case with PHP + MySQL. However, I realized that the data i'm trying to compare both end up using the CURRENT_TIMESTAMP in MySQL so whenever they are updated they end up having the same dates.
Is there a way to just only save the first date the data is inserted into the database (date created) so it doesn't change based on date modified?
Any help is appreciated, thanks in advance!
UPDATE:
my timestamp columns are configured using "DEFAULT CURRENT_TIMESTAMP" not the "ON UPDATE CURRENT_TIMESTAMP" option. Any other work arounds?
UPDATE2:
Please see below for my table definition.
CREATE TABLE IF NOT EXISTS `images` (
`id` varchar(50) NOT NULL,
`patientid` varchar(8) NOT NULL,
`caseid` varchar(25) NOT NULL,
`image_name` varchar(256) NOT NULL,
`status` int(1) unsigned NOT NULL,
`comments` varchar(4000) DEFAULT NULL,
`mod_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Seems like your timestamp columns are configured with "ON UPDATE CURRENT_TIMESTAMP" option, which automatically updates them.
As there does not seem a way to change this on a column, you have to create a new column without that option.
See the TIMESTAMP manual for details visit timestamp-initialization
I'm trying to make a table that has two timestamps columns, one will be for when a row is created and the other for when the row is updated. Here's what I tried so far:
CREATE TABLE `tmp` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`data` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created` timestamp NOT NULL ,
`modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
But I'm getting this error:
Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause
You can do this in MySQL 5.6 (available at the time of writing as release candidate but not yet production-ready).
As of MySQL 5.6.5, TIMESTAMP and DATETIME columns can be automatically initializated and updated to the current date and time (that is, the current timestamp). Before 5.6.5, this is true only for TIMESTAMP, and for at most one TIMESTAMP column per table.... For any TIMESTAMP or DATETIME column in a table, you can assign the current timestamp as the default value, the auto-update value, or both
taken from https://dev.mysql.com/doc/refman/5.6/en/timestamp-initialization.html
This is a MYSQL constraint, You can have only one column whose default value will be the systime.
This question can also be referred
How to add "ON update current timestamp" to existing table column
You could write a trigger to add the created timestamp on inserts seperately
delimiter |
CREATE TRIGGER add_created_ts BEFORE INSERT on `tmp`
FOR EACH ROW
BEGIN
SET NEW.created = current_timestamp;
END
|
delimiter ;
Using PHP I'm inserting a record in a MySQL database. If the record is new I get the insert_id but if it already exists I can't get the id using a single query.
Both of the following queries allow me to add the record or skip if it already exists:
INSERT INTO `emails` (`email`) VALUE ('abc#example.com') ON DUPLICATE KEY UPDATE `id`=`id`
INSERT IGNORE INTO `emails` (`email`) VALUE ('abc#example.com')
What is the right way to get the right result in both cases?
EDIT: Here's my table syntax:
CREATE TABLE `emails` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I suspect that it's the value of LAST_INSERT_ID that ends up in insert_id.
Quote from the MySQL manual;
To make LAST_INSERT_ID() meaningful for updates, insert rows as follows:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), c=3;
Source: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
I want to do the following:
Select multiple rows on an INNER JOIN between two tables.
Using the primary keys of the returned rows, either:
Update those rows, or
Insert rows into a different table with the returned primary key as a foreign key.
In PHP, echo the results of step #1 out, ideally with results of #2 included (to be consumed by a client).
I've written the join, but not much else. I tried using a user-defined variable to store the primary keys from step #1 to use in step #2, but as I understand it user-defined variables are single-valued, and my SELECT can return multiple rows. Is there a way to do this in a single MySQL transaction? If not, is there a way to do this with some modicum of efficiency?
Update: Here are the schemas of the tables I'm concerned with (names changed, 'natch):
CREATE TABLE IF NOT EXISTS `widgets` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`author` varchar(75) COLLATE utf8_unicode_ci NOT NULL,
`text` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
`created` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated` timestamp
NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS `downloads` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`widget_id` int(11) unsigned NOT NULL,
`lat` float NOT NULL,
`lon` float NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
);
I'm currently doing a join to get all widgets paired with their downloads. Assuming $author and $batchSize are php vars:
SELECT w.id, w.author, w.text, w.created, d.lat, d.lon, d.date
FROM widgets AS w
INNER JOIN downloads AS d
ON w.id = d.widget_id
WHERE w.author NOT LIKE '$author'
ORDER BY w.updated ASC
LIMIT $batchSize;
Ideally my query would get a bunch of widgets, update their updated field OR insert a new download referencing that widget (I'd love to see answers for both approaches, haven't decided on one yet), and then allow the joined widgets and downloads to be echoed. Bonus points if the new inserted download or updated widgets are included in the echo.
Since you asked if you can do this in a single Mysql transaction I'll mention cursors. Cursors will allow you to do a select and loop through each row and do the insert or anything else you want all within the db. So you could create a stored procedure that does all the logic behind the scenes that you can call via php.
Based on your update I wanted to mention that you can have the stored procedure return the new recordset or an I'd, anything you want. For more info on creating stored procedures that return a recordset with php you can check out this post: http://www.joeyrivera.com/2009/using-mysql-stored-procedure-inout-and-recordset-w-php/