After Insert Trigger on joomla database gives an error1172 - mysql

I made AFTER INSERT Trigger on joomla database (table _users) which after registration copies user_id and name to another table.
Everything works fine until someone during registration enters a name that already exists Otherwise the column name is not the primary one or unique. I get an error:
Save failed with the following error: Result consisted of more than one row
My trigger looks like this:
BEGIN
DECLARE `new_user` integer;
DECLARE `new_name` VARCHAR(400);
SELECT `id`
INTO `new_user`
FROM `eio3k_users`
WHERE `id` = NEW.id;
SELECT `name`
INTO `new_name`
FROM `eio3k_users`
WHERE `name` = NEW.name;
INSERT INTO `eio3k_point_system`(`user_id`, `name` ) VALUES (NEW.id, NEW.name);
END
What should I do to avoid this error?

Related

Performing SELECT but INSERT when NOT EXISTS in MySQL

I have a MySQL table created using the following syntax:
CREATE TABLE `name_to_id` (
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(128),
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
);
And a common query this table would like to answer is name to id look-up, but if the <name, id> pair does not exist in the DB, then also insert a new entry and return the newly inserted id.
Can I know should I do that in MySQL?
As commented by Strawberry, this cannot be performed in a single query.
However, here is a stored procedure that should do what you expect. First, it uses the INSERT ... ON DUPLICATE KEYS UPDATE syntax to insert new names ; this actually relies on the UNIQUE key that you correctly set up on the name column.
DELIMITER //
CREATE PROCEDURE get_id_by_name(IN p_name VARCHAR(128))
BEGIN
INSERT INTO name_to_id(name) VALUE(p_name) ON DUPLICATE KEY UPDATE name = p_name;
SELECT id FROM name_to_id WHERE name = p_name;
END //
DELIMITER ;
Demo on DB Fiddle.
This approach is efficient, but the downside of ON DUPLICATE KEYS is that it wastes id sequences : everytime the query is called, the sequence is autoincremented (even if a record already exists). This can be seen in the fiddle.
Here is another approach, that won't burn sequence numbers :
DELIMITER //
CREATE PROCEDURE get_id_by_name(IN p_name VARCHAR(128))
BEGIN
DECLARE p_id bigint(20) unsigned;
SELECT id INTO p_id FROM name_to_id WHERE name = p_name;
IF (p_id IS NULL) THEN
INSERT INTO name_to_id(name) VALUE(p_name);
SELECT LAST_INSERT_ID();
ELSE
SELECT p_id;
END IF;
END //
DELIMITER ;
Demo on DB Fiddle.
you can do this on stored proc, if the select statement did not return a result, then you can execute the insert statement

How can I update MySQL table row's when 'BEFORE UPDATE' trigger is firing?

I created a table
Databases Name - mytrigger;
Table name - employee_audit
use mytrigger;
create table employee_audit(
id int auto_increment primary key,
employeeNumber int not null,
lastName varchar(50) not null,
changee datetime default null,
action varchar(50) default null
);
After that, I created one update trigger
My trigger name is
before_employees_update
DELIMITER $$
create trigger before_employees_update
before update on employee_audit
for each row
begin
insert into employee_audit
set action ='update',
employeeNumber = OLD.employeeNumber,
lastName = OLD.lastName,
changee = now();
end$$
DELIMITER ;
After that, I inserted values in table using this command ->
insert into employee_audit values(1,112,'prakash','2015-11-12 15:36:20' ,' ');
After that, I want to update my table row where id =1
update employee_audit set lastName = 'Sharma' where employeeNumber =112;
But it is not executed give an error
ERROR 1442 (HY000): Can't update table 'employee_audit' in stored
function/trigger because it is already used by statement which invoked
this stored function/trigger.
When I searched on Google I found a lot of Question with the same error. But not able to fix my problem. what is the reason I'm not able to update my row?
What i suggest,you can create one log table like employee_audit_LOG .
And on every insert or update in main table you can make new entry in this table or update existing record.
Also you can add updated_timestamp column to that LOG table which maintain when did specific record get updated.
The error itself tells you the answer. This is because, you can't use the same table on which trigger is being executed. You need to store your audit logs into some different table.

Update value each time new rows is created

I have two tables: config(last_inserted_id) and element(id) is there any chance to get the last inserted id any time when new rows are created in element table and execute a update in column last_inserted_id at config table?
I have wrote this:
CREATE TRIGGER UPDATE_CONFIG_VALUES AFTER INSERT ON element
BEGIN
UPDATE config SET last_inserted_id = last_insert_id();
END;
END;
Is that right? What happen if I delete a row in element table? Should the value get updated in config table or not" How I avoid this?
config table
CREATE TABLE IF NOT EXISTS `cmplatform`.`isrl_config` (
`id` INT NOT NULL AUTO_INCREMENT,
`logo_address` VARCHAR(250) NOT NULL,
`name` VARCHAR(250) NOT NULL,
`rif` VARCHAR(20) NOT NULL,
`address` TEXT NOT NULL,
`phone` VARCHAR(14) NOT NULL,
`last_retention_number` INT NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
TEST this ( Not tested)
CREATE TRIGGER element_inserted_tg AFTER INSERT ON element
FOR EACH ROW
BEGIN
DECLARE count INT;
SELECT COUNT(1) INTO count FROM config;
IF count == 1
UPDATE config SET last_inserted_id = NEW.id;
ELSE
INSERT INTO config VALUES (NEW.id);
END IF;
END;
CREATE TRIGGER element_deleted_tg AFTER DELETE ON element
FOR EACH ROW
BEGIN
UPDATE config SET last_inserted_id = (SELECT MAX(id) FROM element);
END;
Trigger is traditional way to do this requirement but not unique way. Another way is process it in your data access code. Let say that you have a DAO method to create new Element, you can get the id of element created and update it into last_inserted_id. If you do this way, you have to makesure there is ONLY ONE THREAD calling insert element method at a time.

How to prevent creation of records where the value of two fields is the same?

I have the following table.
CREATE TABLE people(
first_name VARCHAR(128) NOT NULL,
nick_name VARCHAR(128) NULL
)
I would like to prevent people from having their nickname be the same as their firstname if they attempt that insertion. I do not want to create an index on either of the columns just a rule to prevent the insertion of records where the first_name and nick_name are the same.
Is there a way to create a rule to prevent insertion of records where the first_name would equal the nick_name?
CREATE TRIGGER `nicknameCheck` BEFORE INSERT ON `people` FOR EACH ROW begin
IF (new.first_name = new.nick_name) THEN
SET new.nick_name = null;
END IF;
END
Or you can set first_name to NULL which will cause SQL error and you can handle it and show some warning.
You only need triggers for BEFORE INSERT and BEFORE UPDATE. Let these check the values and abort the operation, if they are equal.
Caveat: On older but still widely used versions of MySQL (before 5.5 IIRC) you need to do something bad, such as read from the written table or easier read from an inexistant table/column (in order to abort).
AFTER INSERT trigger to test and remove if same ...
CREATE TABLE ek_test (
id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
one INT NOT NULL,
two INT NOT NULL
);
delimiter //
CREATE TRIGGER ek_test_one_two_differ AFTER INSERT ON ek_test
FOR EACH ROW
BEGIN
IF (new.one = new.two) THEN
DELETE FROM ek_test WHERE id = new.id;
END IF;
END//
delimiter ;
INSERT INTO ek_test (one, two) VALUES (1, 1);
SELECT * FROM ek_test;
NOTE you will also need AFTER UPDATE trigger.

MySQL trigger delete passing user ID

I need to create MySQL trigger that would log user ID on delete table row statement which must fit in one query, since I'm using PHP PDO. This is what I've come up so far:
I need the way to pass user ID in the delete query even though it is irrelevant to delete action to be performed:
Normally the query would look like this:
DELETE FROM mytable WHERE mytable.RowID = :rowID
If I could use multiple queries in my statement, I would do it like this:
SET #userID := :userID;
DELETE FROM mytable WHERE mytable.RowID = :rowID;
This way the variable #userID would be set before trigger event fires and it can use it. However since I need to squeeze my delete statement in one query, so I came up with this:
DELETE FROM mytable
WHERE CASE
WHEN #userID := :userID
THEN mytable.RowID = :rowID
ELSE mytable.RowID IS NULL
END
Just a note: RowID will never be null since it's the primary key. Now I have to create a delete trigger to log the user ID to the audit table, however I suppose that in this case trigger will be fired before the delete query itself which means that #userID variable will not be created? This was my idea of passing it as a value to the trigger.
I feel like I'm close to the solution, but this issue is a blocker. How to pass user ID value to the trigger without having multiple queries in the statement? Any thoughts, suggestions?
You can use NEW / OLD mysql trigger extensions. Reference: http://dev.mysql.com/doc/refman/5.0/en/trigger-syntax.html
Here is a sample code :
drop table `project`;
drop table `projectDEL`;
CREATE TABLE `project` (
`proj_id` int(11) NOT NULL AUTO_INCREMENT,
`proj_name` varchar(30) NOT NULL,
`Proj_Type` varchar(30) NOT NULL,
PRIMARY KEY (`proj_id`)
);
CREATE TABLE `projectDEL` (
`proj_id` int(11) NOT NULL AUTO_INCREMENT,
`proj_name` varchar(30) NOT NULL,
`Proj_Type` varchar(30) NOT NULL,
PRIMARY KEY (`proj_id`)
);
INSERT INTO `project` (`proj_id`, `proj_name`, `Proj_Type`) VALUES
(1, 'admin1', 'admin1'),
(2, 'admin2', 'admin2');
delimiter $
CREATE TRIGGER `uProjectDelete` BEFORE DELETE ON project
FOR EACH ROW BEGIN
INSERT INTO projectDEL SELECT * FROM project WHERE proj_id = OLD.proj_id;
END;$
delimiter ;
DELETE FROM project WHERE proj_id = 1;
SELECT * FROM project;
SELECT * FROM projectDEL;