How to trigger correctly in MySQL? - php

I am trying to use a trigger from MySQL with these conditions. And I am really a new to use MySQL.
My Steps:
1) Update before changes on table A
2) I have 2 fields in these table A: FieldToSum (with 1 or 0 in many rows) and SUM (that have to be updated, querying the sum of FieldToSum data.
3) My code doesn´t work:
DELIMITER $$
CREATE TRIGGER before_sums
before update ON tableA
BEGIN
UPDATE tableA SET SUM=select sum(FieldToSum) from tableA;
END
$$

Related

mysql trigger limit the number of rows inserted for the id column

I would like my website's users to submit data with my HTML form. However, I want each user to be limited to 5 submissions total. To do this, I'm using a MySQL DML trigger to limit my column "um_id" to only five rows per id. But, I know my syntax is wrong and I'm asking anyone here to help correct it so that it could actually work.
Right now I'm testing this in PHPMyAdmin and it will eventually be placed in my PHP file. So um_id will have a value and be concatenated with this SQL Trigger.
CREATE TRIGGER ml_trigger
BEFORE INSERT
ON ml_character;
BEGIN
IF ( SELECT . 'um_id' . COUNT(*) > 5 ) THEN ROLLBACK;
END IF;
Something like this:
DELIMITER $$
CREATE TRIGGER ml_trigger_bi
BEFORE INSERT
ON ml_character
FOR EACH ROW
BEGIN
-- get count of existing rows with same um_id
DECLARE li_cnt BIGINT;
SELECT COUNT(*) AS cnt
FROM ml_character t
WHERE t.um_id = NEW.um_id
INTO li_cnt ;
-- if already five rows, throw error
IF li_cnt >= 5 THEN
SIGNAL '45000' SET MESSAGE_TEXT = 'Already five rows in ml_character';
END IF;
END$$
DELIMITER ;
The value of um_id to be checked will come from the row being inserted; we reference that value as NEW.um_id.

Mysql auto insert on new table

Can anyone explain me what below code actually do, I have this on my mysqlDB.sql exported file
DROP TRIGGER IF EXISTS `alertupdateevent`;
DELIMITER $$
CREATE TRIGGER `alertupdateevent` AFTER INSERT ON `RECOG`
FOR EACH ROW BEGIN
INSERT INTO `mydb`.`ALERTUPDATES` (`FIRSTNAME`, `LASTNAME`, `CAMNAME`, `TIMESTAMP`, `RESERVE1`, `ALERTTYPE`, `IMGURL`) VALUES (NEW.FIRSTNAME, NEW.LASTNAME, NEW.DOB, NEW.TIMESTAMP, NEW.FACEID, 'RECOG' , NEW.FACEURL);
END
$$
DELIMITER ;
Currently I dealing a project which is not developed by me, and I am not well familiarized with mysql.
The problem I am facing is I have two table in DB like RECOG and ALERTUPDATES and I need to insert data to both of these table(same data), and I can see only one php which insert data to the table `RECOG'.
So my question does the above piece of code insert data automatically to table ALERTUPDATES when data insert on RECOG table by php.
Yes, you are correct.
Trigger are used to INSERT UPDATE on some TABLE based on action perform on some TABLE actions like insert, update or delete.
Refer MySQL triggers
Try this..
CREATE TRIGGER trigger_name
BEFORE INSERT
ON table_name FOR EACH ROW
BEGIN
-- variable declarations
-- trigger code
END;
Parameters or Arguments
trigger_name
The name of the trigger to create.
BEFORE INSERT
It indicates that the trigger will fire before the INSERT operation is executed.
table_name
The name of the table that the trigger is created on.
RESTRICTIONS
You can not create a BEFORE trigger on a view.
You can update the NEW values.
You can not update the OLD values.
Example:
DELIMITER //
CREATE TRIGGER contacts_before_insert
BEFORE INSERT
ON contacts FOR EACH ROW
BEGIN
DECLARE vUser varchar(50);
-- Find username of person performing INSERT into table
SELECT USER() INTO vUser;
-- Update create_date field to current system date
SET NEW.created_date = SYSDATE();
-- Update created_by field to the username of the person performing the INSERT
SET NEW.created_by = vUser;
END; //
DELIMITER ;
Ref:http://www.techonthenet.com/mysql/triggers/before_insert.php

Trigger calculation, on insert of one table effect on other table

IDEA:
Having a table of item, user, assign now if I assign one item to user which the record will be save on table of assign,
table_item:
ID------INT
NAME----TEXT
COUNT---INT
table_user:
ID-------INT
NAME-----TEXT
table_assing:
ID------INT
USER----INT (user id)
ITEM----INT (item_id)
COUNT---INT (this is for subtractions from the column of COUNT table of item)
Here I want to set trigger on inserting to table (table_assing) the value of column COUNT should subtract from column of COUNT table of table_item
This is possible on PHP that I can set to query on once action but it will take lots of code if it's possible on MySQL that will be much better and fast and effective with accuracy
simple trigger after insert on table table_assign
UPDATE table_item
SET table_item.count = (table_item.count - NEW.table_assign.count)
WHERE table_item.id = table_assign.item
Something like this should work.
DELIMITER $$
USE database_name$$
CREATE TRIGGER trigger_name AFTER INSERT ON table_asign FOR EACH ROW
BEGIN
UPDATE table_item SET count=count+NEW.count WHERE id=NEW.id;
END;$$
The 'NEW.id' refers to the new row in the table 'table_asign'

MySQL Timestamp when update a specific column with PHP

I want to put a timestamp when a specific column is updated.
For example:
column1: a value
dateColumn1: date column1 was updated
column2 : a value
dateColumn2: date column2 was updated
I use the function getTimestamp(), but it doesn't seem to work.
Can anyone advise me on how to do this in PHP and MYSQL?
Thanks.
If you want to do this only in the database, you could write a trigger that checks your conditions and updates specific timestamps if needed. But I'm assuming you don't want to fiddle around with triggers. Triggers have an advantage though: you can access the old and the new values of a row without having to write any php code.
Anyway, in case you need it here is some example code for a trigger (SQL, beware):
DELIMITER $$
DROP TRIGGER IF EXISTS Table1_UpdateTrigger $$
CREATE TRIGGER Table1_UpdateTrigger BEFORE UPDATE ON Table1
FOR EACH ROW BEGIN
IF OLD.column1 != NEW.column1 THEN
SET NEW.dateColumn1 = NOW();
END IF;
IF OLD.column2 != NEW.column2 THEN
SET NEW.dateColumn2 = NOW();
END IF;
END;
$$
DELIMITER ;
Substite Table1 with your real table names, column1, etc. with real column names.
The other way is to compare the old and the new values in php. E.g. do a query fetching the old data, compare the fields you want to check, and then do one update query per field that has changed to set the new timestamps.
UPDATE table
SET column1='new value', timestampcolumn=NOW()
WHERE ...
is one way. If you don't mind the timestamp changing anytime anything in the record is updated, then use the native "timestamp" field type, which'll update itself to "now" when the record's inserted or changed.
I prefer using the MySQL function NOW(), like so:
UPDATE table1 SET column2 = value, dateColumn2 = NOW() WHERE somethingsomething
Use a conditional statement. For example in the following trigger the 'password changed time' will be updated only when there is change in password column.
CREATE TRIGGER update_password
BEFORE UPDATE ON users
FOR EACH ROW
BEGIN
IF OLD.password <> NEW.password THEN
SET NEW.password_changed_on = NOW();
END IF;
END //

mysql - create indexed hour column from existing timestamp

I have a column 'updatetime' that is a timestamp ("2011-02-01 09:00:51"). For performance purposes I need to create an indexed column 'updatetime_hour' based on the hour of the timestamp.
So for example if 'updatetime' was "2011-02-01 09:00:51" then 'updatetime_hour' would be "9".
I'm trying to do this all in mysql though PHP is an option as well. 60k+ existing rows.
Thoughts?
UPDATE yourtable SET updatetime_hour=HOUR(updatetime);
Don't run this in peak hours, it will take a while. You could even run it in smaller batches - make updatetime_hour nullable and continue running this, until you get "0 rows affected":
UPDATE yourtable SET updatetime_hour=HOUR(updatetime)
WHERE updatetime_hour IS NULL LIMIT 1000;
To do this automatically each time you add or update a row, use triggers:
CREATE TRIGGER t1 BEFORE INSERT ON table
FOR EACH ROW BEGIN
SET NEW.updatetime_hour = HOUR(NEW.updatetime);
END
CREATE TRIGGER t2 BEFORE UPDATE ON table
FOR EACH ROW BEGIN
SET NEW.updatetime_hour = HOUR(NEW.updatetime);
END

Categories