Update TimeStamp on Single Column Update - php

I have one table called number_list which have columns like:
id, name, number, server, status, last_act, user_id, created_at, disable, notify,fcm
I want update last_act when there any changes in status column only. Currently its updating last_act whenever any changes in any column.
Let me know if its possible with MySQL. Thanks

Setting up a trigger like the following should accomplish what you have asked.
DELIMITER $$
CREATE TRIGGER number_list_update_trigger
BEFORE UPDATE
ON number_list
FOR EACH ROW
BEGIN
if (NEW.status = OLD.status) THEN
set NEW.last_act = OLD.last_act;
END IF;
END $$
DELIMITER ;

Related

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'

Insert distinct records in the table while updating the remaining columns

This is actually a form to update the team members who work for a specific client, When i deselect a member then it's status turns to 0.
I have a table with all unique records. table consists of four columns -
first column is `id` which is unique and auto_incremented.
second column is `client_id`.
third column is `member_id`. (these second and third columns together make the primary key.)
fourth column is `current` which shows the status (default is 1.).
Now i have a form which sends the values of client_id and member_id. But this forms also contains the values that are already in the table BUT NOT ALL.
I need a query which
(i) `INSERT` the values that are not already in the table,
(ii) `UPDATE` the `current` column to value `0` which are in the table but not in the form values.
here is a screenshot of my form.
If (select count(*) from yourtable where client_id = and member_id = ) > 0 THEN
update yourtable set current = 0;
ELSE
insert into yourtable (client_id,member_id,current) values (value1,value2,value3)
First of all check if the value exists in the table or not, by using a SELECT query.
Then check if the result haven't save value so it will be inserted, else show an error .
This would be a great time to create a database stored procedure that flows something like...
select user
if exists update row
else insert new row
stored procedures don't improve transaction times, but they are a great addition to any piece of software.
If this doesn't solve your problem then a database trigger might help out.
Doing a little research on this matter might open up some great ideas!
Add below logic in your SP
If (select count(*) from yourtable where client_id = <value> and member_id = <value>) > 0 THEN
update yourtable set current = 0;
ELSE
insert into yourtable (client_id,member_id,current) values (value1,value2,value3)
if you want simple solution then follow this:
*) use select with each entry in selected team.
if select returns a row
then use update sql
else
use insert sql.
In your case member_id & client_id together makes the primary key.
So , you can use sql ON DUPLICATE KEY UPDATE Syntax.
Example:
$sql="INSERT INTO table_name SET
client_id='".$clientId."',
member_id='".$member_id."',
current='".$current."'
ON DUPLICATE KEY
UPDATE
current = '".$current."'
";
In this case when member_id & client_id combination repeats , it will automatically executes update query for that particular row.

Help with MySql trigger or alternative

I am trying to bring together two separate designs here so I understand the overall approach may not be ideal. Basically through user input in PHP table1 and part of table2 is populated and then in turn I need the rest of table2 and table3 to be populated automatically.
I have the following db
with this trigger
DELIMITER |
CREATE TRIGGER new_trigger AFTER INSERT on table2
FOR EACH ROW BEGIN
INSERT INTO table3(att1, DateCreated, DateUpdated)
VALUES('PG', now(), now());
UPDATE table2 SET table3Id = table3.LAST_INSERT_ID();
END;
|
DELIMITER ;
although MySQL accepts the trigger as written without any errors I get this error when the app runs:
General error: 1442 Can't update table 'table2' in stored function/trigger
because it is already used by statement which invoked this stored function/trigger
I believe this comes from MySQL triggers can't manipulate the table they are assigned to. So if this is the reason for the error how else can I achieve the same results?
EDIT: (ANSWER)
Thanks to the help from mootinator here and in chat. Here is his solution that works as I need it to.
CREATE TRIGGER new_trigger BEFORE INSERT on table2
FOR EACH ROW BEGIN
INSERT INTO table3(att1, DateCreated, DateUpdated)
VALUES('PG', now(), now());
SET NEW.table3Id = LAST_INSERT_ID();
END;
You can't use an AFTER trigger because the new change you make would (potentially) cause the AFTER trigger to be run again in an infinite loop. You have to use a BEFORE trigger to edit the row before it gets written.
Try eg:
CREATE TRIGGER new_trigger BEFORE INSERT on table2
FOR EACH ROW BEGIN
INSERT INTO table3(att1, DateCreated, DateUpdated)
VALUES('PG', now(), now());
SET NEW.table3Id = LAST_INSERT_ID();
END;

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 //

Categories