Retrieving values from an Insert that called a trigger - mysql

There are two tables itemsand items_history, after an insert occurs in the itemstable I'm looking to insert an entry into the items_historytable using the below trigger.
I'm a little confused and concerned I'm not doing it correctly, I'm creating two variables NEW.iidand NEW.ip these are both values inserted on the insert that called the trigger. Am I doing it correctly to get the two values and insert them into the items_history table or is there a better more efficient way to do it?
iid on the items_historytable is a FOREIGN KEY of id on the itemstables.
DROP TRIGGER IF EXISTS `item_created_trg`;
CREATE TRIGGER `item_created_trg`
AFTER INSERT ON `items` FOR EACH ROW
BEGIN
SET NEW.iid = (SELECT MAX(id) FROM `items` LIMIT 1);
SET NEW.ip = (SELECT created_ip FROM `items` i WHERE i.id=NEW.iid LIMIT 1);
INSERT INTO `items_history` (iid, title, description, created, created_by, created_ip) VALUES (NEW.iid, 'Added to database.', '', NOW(), 1, NEW.ip);
END;
Thanks in advance.

If I understand you correctly your trigger should look like this
CREATE TRIGGER item_created_trg
AFTER INSERT ON items
FOR EACH ROW
INSERT INTO items_history (iid, title, description, created, created_by, created_ip)
VALUES (NEW.id, 'Added to database.', '', NOW(), 1, NEW.created_ip);
Here is SQLFiddle demo

Related

Mysql: ON DUPLICATE KEY UPDATE: Only update when value has changed

I have a mysql table where I use this query:
INSERT INTO `stats` (`id`, `shop`, `price`, `timestamp`)
VALUES (NULL, '$shop', '$price', 'timestamp') ON DUPLICATE KEY UPDATE price='$price'
The shop column is unique. "Id" = primary key. The timestamp column is updated by mysql: on update CURRENT_TIMESTAMP
Data in the dB:
row: id=1, shop=viacom, price=5, timestamp=1524183480
Case 1: Row to be inserted: shop=viacom, price=6
Result: The existing row is updated
Case 2: Row to be inserted: shop=viacom, price=5 (<-- price has NOT changed)
Result: The existing row is NOT updated
I would like to get case 2 working. I can handle it with php-code, but I'd rather let Mysql do that job. Any ideas? (I tried adding a Where Clause like $shop=shop)
Since the shop column is a UNIQUE key, you can remove the id column and use the below.
replace into stats (shop, price) values ('$shop', '$price')
If shop already exists, then the price is updated. Else a new shop will be inserted. Is this what you want?
Try to update the timestamp column manually:
INSERT INTO `stats` (`shop`, `price`) VALUES ('$shop', '$price')
ON DUPLICATE KEY UPDATE price='$price', timestamp = NOW();
=========
Option #2:
If you want to do it in MySQL, create stored procedure and call the stored procedure from PHP code.
CREATE PROCEDURE `createOrUpdatePrice` (ex_shop varchar(255),ex_price int(11))
BEGIN
declare occures tinyint(1);
SELECT COUNT(`shop`) into occures from `stats` WHERE shop = ex_shop;
IF occures = 0 Then
INSERT INTO `stats` (`id`, `shop`, `price`) VALUES (NULL, ex_shop, ex_price);
ELSE
UPDATE `stats` SET price = ex_price where shop = ex_shop;
END IF;
END

MySQL Multiplication trigger?

I have a table called history with the fields id, g.id, date, value. I want to put a trigger that will update the table when a new row is inserted and divide the number inserted in the value field by 2.
I have been trying for hours with no luck, any help would be appreciated.
for eg, after
INSERT INTO `online_game_shop`.`history`
(`id`, `gameID`, `dateofPurchase`, `Value`)
VALUES ('1001', '101', '2014-02-22', '10');
so the trigger will automatically divide 10 by 2 and update the field with result.
CREATE TRIGGER pointstovalue
AFTER INSERT ON history
FOR EACH ROW
BEGIN
UPDATE history
SET value = new.value/2
WHERE history.id = NEW.id
END;
You want a before insert trigger:
CREATE TRIGGER pointstovalue
BEFORE INSERT ON history
FOR EACH ROW
BEGIN
set new.value = new.value/2;
END;

Mysql query INSERT two tables

I have two tables:table1 and rating
table1(id,name,category)
rating (cid,rating,total_rating,total_rates,photoID)
and now when i insert data into table1 i want to set all data in table rating at zero for that specific photoID from table1, but i dont know how..can someone help me?
You can use LAST_INSERT_ID() to retrieve the ID you just inserted. For example, assuming PhotoID is the relation between table1 and rating:
insert table1 (name,category) values ('waterfall 2', 'nature');
insert rating (rating,total_rating,total_rates,photoID) values
(0, 0, 0, last_insert_id());
I'd rather create a STORED PROCEDURE to make a single call from application. Assuming that you want to INSERT a record on table rating for every insert on table1 and that ID on table1 is set as AUTO_INCREMENT.
DELIMITER $$
CREATE PROCEDURE procedureName
(
IN _name VARCHAR(25),
IN _category VARCHAR(25)
)
BEGIN
INSERT INTO table1 (name, category)
VALUES (_name, _category);
SET #last_ID := LAST_INSERT_ID();
INSERT INTO rating (cid, rating, total_rating, total_rates, photoID)
VALUES (#last_ID, 0,0,0,0);
END $$
DELIMITER ;
and call the procedure,
CALL procedureName('nameHere','categoryHere')
You can use MySql triggers http://dev.mysql.com/doc/refman/5.0/en/trigger-syntax.html:
CREATE TRIGGER ins_rating AFTER INSERT ON table1
FOR EACH ROW
BEGIN
INSERT INTO rating (cid,rating,total_rating,total_rates,photoID)
VALUES( NEW.ID ,0,0,0,null)
END;
If you want to insert data into TABLE1 and delete it from TABLE2, you can write below listed query:
mysql_query("DELETE * FROM table2");

mysql - trigger table change

I want to trigger an alert on screen when some changes made to my mysql tables using PHP.
Currently, I have many tables with different structures (Purchase Order, Sales Order, Users etc), my intention is to make a real-time application, but the problem is that I have already written 90% of the application.
I have a table with name activity
It Contains:
id, table, action, dateTime, user
When some changes are made to Purchase Order table, then I need to log
(0,'TABLE A','INSERT','12/12/12','John')
so that I can show JOHN created a new Purchase Order.
Please note that I have already written many parts of the application, what will be the most possible way to achieve this ?
If your question is how to log changes in activity table then you can create triggers on every table (orders, sales, users etc) that you want to monitor like this:
CREATE TRIGGER `tg_orders_insert` AFTER INSERT ON orders
FOR EACH ROW INSERT INTO `activity` (`id`, `table`, `action`, `date_time`, `user`) VALUES (NEW.id, 'orders', 'insert', NOW(), 'user1')
CREATE TRIGGER `tg_orders_update` AFTER UPDATE ON orders
FOR EACH ROW INSERT INTO `activity` (`id`, `table`, `action`, `date_time`, `user`) VALUES (NEW.id, 'orders', 'update', NOW(), 'user1')
CREATE TRIGGER `tg_orders_delete` BEFORE DELETE ON orders
FOR EACH ROW INSERT INTO `activity` (`id`, `table`, `action`, `date_time`, `user`) VALUES (OLD.id, 'orders', 'delete', NOW(), 'user1')

MYSQL trigger see if record exists first?

So I have a trigger that works on update. Totally works fine.
Insert in cars(date, id, parent_id) values (date, ford, 2)
What I need to do is to actually check to see if the parent_id already exists. If it does do nothing but if it does not exist then do the insert statement.
right now i have
SET #myVar1 = (SELECT parent_id from cars where parent_id = NEW.id);
IF #myVar1 = NULL;
Insert in cars(date, id, parent_id) values (date, ford, 2);
ENDIF;
I keep getting sysntax error. How am I writing this worng?
The problem is on this line:
Insert in cars(date, id, parent_id) values (date, ford, 2);
The in should be INTO. That's the syntax error.
That said, you might be better served with an INSERT...ON DUPLICATE KEY or REPLACE INTO statement rather than an on-update trigger. Be careful with REPLACE INTO though, as it can be dangerous (but the danger can be somewhat mitigated by using transactions).
dunno if this what you really need. but you can try this one
SET #myVar1 = (SELECT parent_id from cars where parent_id = NEW.id);
IF (#myVar1 is NULL) then
Insert into cars(`date`, id, parent_id) values (date(), new.`name`, new.id);
END IF;
or
Insert into cars(`date`, id, parent_id) values (date(), new.`name`, new.id) on duplicate key update `date`=date();
on mysql must be "end if" not "endif".
new.name is assumes that id field on car from trigger table
you can use on duplicate key update if cars table use primary key or unique key like mention above
and if you doesn't want to change any record if exists then after key update change to id=id or you can use any field.