use trigger with update and insert query both in mysql - mysql

i have login page with user name and password, if the user forgot his/her password then there is a link of forgot password,were one has puts its email id and then the default password will send to its id and it will also update it in table with update query,the problem is that when in future we give this project to client we have truncate whole data and give him empty database, at that time update query won't work at that moment i need to use insert query, so i need a trigger query which fires on insert as well as on update query also later on when data is filled, please help because i never used trigger and i don't know its syntax, please explain me by showing an example

You do not need a trigger. Just run an INSERT INTO...ON DUPLICATE KEY UPDATE query. It will insert a row, but if a row with the same primary key already exists, update the column in the existing row instead.
http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html

Related

What is proper way to set and compare variable inside an sql trigger

Am populating a table using a trigger after an insert event occurs on another table and that worked fine. However i then noticed that the trigger would still insert a new row for existing records. To fix this, I want to create the trigger again but this time it would only fire if a condition is met...but not having previously used triggers in the past am getting a syntax error and not able to identify what am doing wrong. Kindly have a look and help me fix this
CREATE TRIGGER `students_gen_insert`
AFTER INSERT ON `students` FOR EACH ROW
BEGIN
INSERT INTO records (student_id, subject_id)
SELECT new.student_id, subjects.subject_id
FROM subjects
WHERE category = new.class;
END;
Am currently using MySql 5.6.17 version.
It is generally not a good idea to SELECT from the table the trigger is on, and forbidden to UPDATE or INSERT (not that you are doing those). Assuming you are trying to get the values for the row just inserted, the first SET ... SELECT you have is needless; just use NEW.fieldname to get the fields of the inserted row.
The second SET ... SELECT and following condition are a bit confusing. If referential integrity is being maintained, I would think it would be impossible for the records table to refer to that particular student_id of the students table at the point the trigger is executed. Perhaps this was to avoid the duplicate inserts from the trigger's previous code? If so, it might help for you to post that so we can pinpoint the actual source of redundant inserts.

Trigger on Update of a specific field in mySQL

I am trying to replicate the Username field in my database. Specifically I was looking to add/remove the Username across different tables, whenever the row that contains Username is added inside UserDatabase. To that end, I was thinking of using the trigger mechanism.
I am thinking along the lines of:
CREATE TRIGGER 'addUsername' AFTER INSERT ON UserDatabase FOR EACH ROW
IF (UPDATE(Username))
BEGIN
INSERT INTO anothertable (Username) VALUES ('NewUser');
END
My question is that is how do I capture the updated Username from UserDatabase and replicate it into NewUser? And also, is there a way to remove FOR EACH ROW as I only want the loop to run once?
Thanks!
From the manual:
Within the trigger body, you can refer to columns in the subject table (the table associated with the trigger) by using the aliases OLD and NEW. OLD.col_name refers to a column of an existing row before it is updated or deleted. NEW.col_name refers to the column of a new row to be inserted or an existing row after it is updated.
And no, you can not remove for each row and I think you misunderstood it a little. There actually is no loop. for each row refers to multiple rows in your insert or update statement. When you add multiple users with one insert statement, you want all of them replicated, right? Not just one.
Then you should note, that there's a difference between single-quotes and backticks. Backticks should be used, if a column or tablename or whatever includes characters that shouldn't be there, like a space, or if the name is actually a reserved keyword. Single-quotes, like you used them for the trigger name are used to tell MySQL it's a string.
Your trigger should look something like this:
CREATE TRIGGER 'addUsername' AFTER INSERT ON UserDatabase
FOR EACH ROW
INSERT INTO anothertable (Username) VALUES (NEW.Username);
For an update statement, you have to create another trigger.

Trigger on a field is fired unexpectedly when I update another field

Here is my table:
Id Password Status
1 a6cc890.. 1
I have a trigger upon Password which is used to encrypt the field.
The trigger is as below:
-- Trigger DDL Statements
DELIMITER $$
USE `ediftpdb`$$
CREATE
DEFINER=`edidbo`#`%`
TRIGGER `ediftpdb`.`trigger_format_passwd`
BEFORE INSERT ON `ediftpdb`.`users`
FOR EACH ROW
SET NEW.passwd=md5(NEW.passwd)$$
CREATE
DEFINER=`edidbo`#`%`
TRIGGER `ediftpdb`.`trigger_format_passwd_update`
BEFORE UPDATE ON `ediftpdb`.`users`
FOR EACH ROW
SET NEW.passwd=md5(NEW.passwd)$$
To my surprise, the trigger is fired when I update Status, and the password is encrypted again!
What should I do to resolve this issue?
If you update Status, you're doing an UPDATE and all of the UPDATE triggers will fire. All you need to do is compare the new and old values of passwd and only apply your MD5 if they are different. Lucky for you, MySQL supplies OLD and NEW row aliases:
You can refer to columns in the subject table (the table associated with the trigger) by using the aliases OLD and NEW. OLD.col_name refers to a column of an existing row before it is updated or deleted. NEW.col_name refers to the column of a new row to be inserted or an existing row after it is updated. Try using IF:
BEFORE UPDATE ON `ediftpdb`.`users`
FOR EACH ROW
SET NEW.passwd = IF(NEW.passwd = OLD.passwd, NEW.passwd, md5(NEW.passwd))
This shouldn't change NEW.passwd unless NEW.passwd (the new password) and OLD.passwd (the hashed password that is already in the database) are different. Of course, this might fail if someone manages to enter the MD5 of their old password as their new password but that's pretty unlikely.
When you "update Status", you're actually performing an UPDATE on the whole table. The fact that you only modify the value of one field doesn't come into it!
You can manually check whether the value of passwd has changed using the NEW and OLD identifiers.

Is it possible to declare to mysql queries?

I'm trying to create a code for a single button where it will perform either of two actions where it will add to the database if the user currently don't have the record while it will update the user's record if the user has records already. I've done it like this:
if() {
mysql_query("INSERT INTO table...");
}
else {
mysql_query("UPDATE table SET...");
}
Is it possible?
Yes, what you've written will work. If you have a way to know if there already exists a row or not without making an additional query just for this bit of code, then do exactly as you wrote.
If, however, you planned to first SELECT from the table to see if a row exists, then conditionally INSERT or UPDATE, you will perform more queries than necessary.
It would be better to either:
Have a PRIMARY KEY or other constraint on the table prevent duplicate INSERTs. Then issue an INSERT ... ON DUPLICATE KEY UPDATE query. This will attempt to INSERT the row, and if it is a duplicate, automatically perform the specified UPDATE to that row instead.
Issue the UPDATE query and check mysql_affected_rows to see if it updated an existing row. If not, then issue the INSERT query to create the new row.
Which one is more appropriate depends on your application.
you can use INSERT ... ON DUPLICATE KEY UPDATE Syntax like:
INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
If you have properly set unique keys, you should use REPLACE so you could remove the if.
REPLACE INTO table VALUE (...);
Pay attention that this is a MySQL extension, thus not portable to other DBs.
Yes, you could try the insert then if it fails try the update.
But you could use the MYSQL sql "REPLACE" keyword, which will insert a new record if it doesn't exist or delete the existing record and insert your new one if it does.
You could also use the INSERT ... ON DUPLICATE KEY UPDATE syntax
(explained here - Link to MYSQL ref which seems to be the closest fit to your requirement.
yes it is possible
first write a query for check that record is already exist or not.
Yes it is possible , it will work

How can I update 2nd table is 1st table is updated in MySQL?

I am having two tables. For example one is Login and the other is calculation. In the login table I am having fields username and password. In calculation I am having username and flag.
Now when any user is added in the login table I want make entry for that user in calculation table also.
How can I proceed for this?
Why not have the flag in the Login table?
In MySQL you should be able to set a 'trigger' on the insert operation on the login table, that can do the second insert for you. See:
http://dev.mysql.com/doc/refman/5.0/en/triggers.html
You might want to handle deletes and/or updates (change of username?) in the same way.
Meder's answer above will certainly work but prehaps the strategy you are looking for involves triggers; this will allow you to automatically update other info when ever row on a specific table is inserted, updated or deleted.
You only have to create trigger once and then any insert from any source to your LOGIN tbale will also update your CALCULATE table.
My SQL Documentation details the statement here.