mysql - trigger table change - mysql

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

Related

How to add row in another mysql table with trigger by the condition

I need a trigger that throws multiple records in one table based on a value from the last record in the other table.
Below I have shared an example I made before. Having too many rows in this example is a serious problem.
INSERT INTO `ct_bookings` (`id`, `order_id`, `client_id`, `order_date`, `booking_date_time`, `service_id`, `method_id`, `method_unit_id`, `method_unit_qty`, `method_unit_qty_rate`, `booking_status`, `reject_reason`, `reminder_status`, `lastmodify`, `read_status`, `staff_ids`, `gc_event_id`, `gc_staff_event_id`)
SELECT LAST_INSERT_ID()+1, `order_id`, `client_id`, `order_date`,
ADDTIME(`booking_date_time`, '2:0:0'), `service_id`, `method_id`, `method_unit_id`, `method_unit_qty`, `method_unit_qty_rate`, `booking_status`, `reject_reason`, `reminder_status`, `lastmodify`, `read_status`, `staff_ids`, `gc_event_id`, `gc_staff_event_id`
FROM `ct_bookings_sub` WHERE method_unit_qty > 99

How do I update in SQL syntax multiple values in the same command MySQL

What I want to do is update the column productName where the value is ='OpenAM' (there are two in this case) but how about when there are more than just two and by mistake a user inputs the same value to all of them now I have to fix them without having to go one by one.
I tried using the IN operator to solve this or is there a better way and the way I am trying to doing this is completely wrong.
this is my table
CREATE TABLE ForgeRock
(`id` int, `productName` varchar(7), `description` varchar(55))
;
INSERT INTO ForgeRock
(`id`, `productName`, `description`)
VALUES
(1, 'OpenIDM', 'Platform for building enterprise provisioning solutions'),
(2, 'OpenAM', 'Full-featured access management'),
(3, 'OpenDJ', 'Robust LDAP server for Java'),
(4, 'OpenAM', 'Full-featured access management2')
;
This is what I am trying to do
UPDATE ForgeRock
SET
productName='New value'
WHERE IN(
'OpenAM'
)

Retrieving values from an Insert that called a trigger

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

mysql IFNULL INSERT huge setback?

I am having a bit of a problem with some mysql. I will try to give a much background as I can. This is the situation, I had created an availability for my parent's plant nursery and stored the plant information in mysql, I did a terrible job the first time and now I am redoing it with the new knowledge I have gained in the mean time.
Background of the problem, I had 2 tables in the old database one being called Gallery with the following fields:
(id, Plant_id_1, Plant_id_2, Plant_id_3, Plant_id_4, Plant_id_5, Image1, Image1_Copyright, Image2, Image2_Copyright, Scientific, Common, Category, Height, Spread, Exposure, Zone, Descp).
The Plant_id_1... fields would be the id of the second table which is called Availability with the following fields:
(id, name, size, description, available, upcomming, price)
So as you can see I knew nothing about datases(still might not) but on to the new structure for the table, again 2 tables the first being called plants with the following fields:
(id, scientific_name, common_name, category, height, spread, exposure, usda, description, image1_url, image1_copyright, image2_url, image2_copyright)
The second being called current with the following fields:
(id, plant_id, size, available, upcoming, price, description)
The plant_id will be the id of the corresponding plant in the plant table.
Now on to the problem. I need to get the data from the old table and put it into the new table. I have all the plants from gallery in the new plant table no issue there. But now to get the Availability into the Current table.
This is an example from the export of the Availability (I took the top 3):
INSERT INTO `Availability` (`id`, `name`, `size`, `description`,`available`, `upcomming`, `price`) VALUES(91, 'Acer P.''Shishigashira''', ' #5', '30-36"', 27, 0, 36.00);
INSERT INTO `Availability` (`id`, `name`, `size`, `description`, `available`,`upcomming`, `price`) VALUES(697, 'Arbutus U. ''Compacta''', ' #5','', 0, 0, 16.20);
INSERT INTO `Availability` (`id`, `name`, `size`, `description`, `available`, `upcomming`, `price`) VALUES(90, 'Acer P.''Shigitatsusawa''', '#15', '', 0, 0, 65.00);
I need to get the plant_id from the plant table and put that into a insert statement, which I believe I have with the following:
INSERT INTO `current` (`plant_id`, `size`,`description`, `available`, `upcoming`, `price`) VALUES(
(SELECT `id`
FROM `plants`
WHERE `scientific_name`
REGEXP 'Acer P.+ ''Shishigashira'''), ' #5', '30-36"', 27, 0, 36.00);
But now I have a new problem what if there is no plant in the plant table to match, So i need a ifnull in there. to create the plant with the scientific name and the rest null. well I am new to SQL so this is what I have and its not working:
INSERT INTO `current` (`plant_id`, `size`,`description`, `available`, `upcoming`, `price`) VALUES(
(IFNULL( SELECT IFNULL( (SELECT `id`
FROM `plants`
WHERE `scientific_name`
REGEXP 'Chamaecyparis O.+ Nana'),(
INSERT INTO `plants` (`scientific_name`)
VALUES (Chamaecyparis O. 'Nana'))))), ' #1', '', 0, 0, 9.25);
As you can see Its very complicated if you think you are up to the challenge of helping me i would beyond greatly appreciated. If no one can help me I will have to manually reenter all the data into the current table.
You should work towards a select that returns the data you need to insert into your new table. Once
you have that you can simply wrap that into a INSERT INTO - SELECT contruction. That way you don't have to export and do individual inserts. You can simply copy the whole set over in one go.
If you make sure that when you copy plants from the gallery into the plants table the id's stay intact I expect a select like this should return the rows you want to insert:
SELECT
Gallery.id as plant_id,
Availability.size,
Availability.available,
Availability.upcoming,
Availability.price,
Availability.description
FROM Gallery
INNER JOIN Availability
ON Gallery.Plant_id1 = Availability.id
Then you can do the same thing 5 times where you change the
ON Gallery.Plant_id1 = Availability.id
to (one by one)
ON Gallery.Plant_id2 = Availability.id
ON Gallery.Plant_id3 = Availability.id
ON Gallery.Plant_id4 = Availability.id
ON Gallery.Plant_id5 = Availability.id
Or you put all of them together in one huge sql statement with a UNION ALL between each select

Multiple insert in multiple tables if nonindexed field not exists

I have a task to update existing multiple product-related tables with new entries if product name doesn't exist (no update). Thing is that this is one time action so product name column is not and will not be set as unique, primary, etc (and it is not possible for me to change it anyway).
I would be delighted if i could access the database remotely and use PHP, but due to security reasons i have access only to PhpMyAdmin on that server.
After googling for couple of hours i realized that either all results are about single INSERT IGNORE or similar constructions, or they are too complicated for me non-mysql brain to understand or solutions just won't work (like IF statement throws syntax error on that 5.5.8 MySQL server.
So thing is - there are 7 tables with all kinds of information on product (product, variant, image, category, product relation to category, prices, discounts). I have to check if product name doesn't exist and if true then insert new entries in all 7 tables. Additionaly i should create new product category entry if such doesn't exist (again, by name, not id)
In my humble opinion it would be like this:
IF (SELECT ProductName from `product` where ProductName='Pony') IS NULL THEN
INSERT INTO `product` VALUES ('', 'Pony');
#productId = (SELECT LAST_INSERT_ID());
INSERT INTO `category` (Name) SELECT 'Everything Nice' FROM `category` WHERE NOT EXISTS (SELECT Name FROM `category` WHERE Name='Everything Nice') LIMIT 1;
SET #categoryId = (SELECT CategoryId FROM `category` WHERE Name='Everything Nice');
INSERT INTO `product_rel_category` VALUES (#productId, #categoryId);
INSERT INTO `variant` VALUES ('', 'Nice');
#variantId = (SELECT LAST_INSERT_ID());
INSERT INTO `product_rel_variant` VALUES (#productId, #variantId);
INSERT INTO `variant` VALUES ('', 'Sweet');
#variantId = (SELECT LAST_INSERT_ID());
INSERT INTO `product_rel_variant` VALUES (#productId, #variantId);
INSERT INTO `variant` VALUES ('', 'Pink');
#variantId = (SELECT LAST_INSERT_ID());
INSERT INTO `product_rel_variant` VALUES (#productId, #variantId);
... etc ...
ENDIF;
MySQL yells about syntax on IF in such query. I also tried working all kinds of procedures, but since I know only 'insert, update, select, delete', there is nothing much i can compose now.
So do you have an advise on solution on how i can make multiple INSERT/SELECT queries if a value in one table doesn't exist.
Sincerely thanks.