PHP MyAdmin After Update Trigger not working - php

I am using PHP MyAdmin Version 4.1.12.
I am trying to create a simple trigger that, after an update, sets 'dateModified' in table 'person' to CURRENT_TIMESTAMP. dateModified is of type TIMESTAMP. The way in which the update occurs to person is the setting of a single attribute in a single record through a X-Editable enabled grid view on a web page. After performing validation against the model with the updated attribute, a new database command is created with the relevant update SQL and executed. So each update only ever modifies a single row within 'person'.
Here is the SQL I wrote to create the trigger:
DELIMITER |
CREATE TRIGGER PERSON_AUPD AFTER UPDATE ON person
FOR EACH ROW BEGIN
SET #dateModified = CURRENT_TIMESTAMP ;
END;
|
DELIMITER ;
After performing updates, I see that the trigger hasn't fired, and the timestamp remains unchanged from the one they were created with (the default for dateModified, and dateCreated, are both CURRENT_TIMESTAMP, so they get set automatically on insert).
I have looked around for answers, and even looked into alternate methods to getting the update (the alternate method was calling a model's afterupdate method and performing separate SQL there on dateModified). I would prefer to exhaust every opportunity to use the triggers, before I go putting more code into my model.
Any help would be greatly appreciated.

Thanks to #juergend, the solution was the following:
Set trigger type to before update because after update cannot update attributes, and are best used to insert new records in related audit tables, etc.
Add NEW. to the front of the attribute you wish to modify.

Related

How to solve Concurrency issue?

All,
I am using MySql 5.7 in my application. I trying to make my save function Concurrency Safe. I will explain with an example.
Example :
I have two admin users Admin 1 and Admin 2. We have a product table and we have a product table entry with product code "P1". Suppose Admin 1 and Admin 2 are logged into the system and try to update product entry with code "P1" at the same time.
I need to inform one of the users that the record(s) you are trying modify is updating by another user and try again after some time.
I am using transaction and didn't change MySql's default transaction level(repeatable read). I am trying to solve it by using "SELECT FOR UPDATE"(included a where condition to check with modified time). This "where" condition will solve concurrency issue to those transactions which are already committed. But if two transaction starts at the same time and the first transaction gets committed before lock timeout, then when the second transaction executes, it overwrites the first one.
Kindly share your ideas
Thanks in advance
Well there are actually 2 issues here.
First, one of the admins will get a lock on the row before the other, so assuming admin1 gets the lock first, admin2 will queue until admin1's transaction completes, then admin2's transaction will take place.
So that is all looked after for you by the DBMS.
But the second issue is of course if both admin1 and admin2 are attempting to update the same column(s). In this case admin1's update will be overwritten by admin2's update. The only way to stop this happening if that is what you want to stop is to make the UPDATE very specific about what it is updating. In other words the UPDATE must be something like this
UPDATE table SET col1 = 'NewValue'
WHERE usual criteria
AND col1 = 'Its Original Value'
So this means that when you present the original data from this row to the user in a form, you must somehow remember what its original state was as well as capture its new state that the admin changed it to.
Of course the PHP code will also have to be written to capture the fact the UPDATE did not take place and return something to whichever admin's update has now failed. Showing the new value in the column in question and giving them a notice that the update failed because someone else already changed that field, and letting them either forget there change, or apply their change over the top of the other admins update.
There is this technique you can use to control it without locking the table or controlling the update you should do.
Create a field on your table that will be a version for that registry:
alter table someTable add column version not null integer default 0;
There will be no need to change any insert code with this.
Every time a user fetches a registry to update you make sure that it will have the version also in the object (or form,m or whatever way you handle your entity in the system).
Then you will need to Create a before update trigger for your table that will check if the version of the current registry is still the same is so you update if not you raise an error. Something like:
delimiter $$
create trigger trg_check_version BEFORE UPDATE
ON yourTable
for each row
begin
if NEW.version != OLD.version then
signal sqlstate '45000' set message_text = 'Field outdated';
else
NEW.version = NEW.version + 1;
end if;
end$$
delimiter;
Then you handle the error in your php code. This signal command will only work on MySql 5.5 or later. Check out this thread

Where and when does this view get populated with data?

I've recently been handed a Yii project (PHP) developed by another developer and I've been assigned to take over it's maintenance.
In the database there is the following VIEW that holds data for certain records in other tables. The view gets -somehow- updated frequently as it contains recent records, meaning that somewhere/somehow rows are constantly being added to it.
However, it's not being referenced as part of the project, meaning it's not defined in a model, controller or anywhere else inside the project whatsoever. I've also gone through the database triggers to see where this view gets its data from but I fail to connect the ends.
I thought there might be a cron job that adds data to it but nada.
So, I'm pretty stuck and in awe. Any ideas on how I could find WHEN this views is either dropped and recreated or where I can find which database action functions as a trigger for inserting rows to it?
DELIMITER $$
ALTER ALGORITHM=UNDEFINED DEFINER=`user_name`#`` SQL SECURITY DEFINER VIEW `VW_viewname` AS
SELECT
`DOM`.`CustomerID` AS `CustomerID`,
`DOM`.`User` AS `User`,
`DOM`.`DemoOrderDate` AS `DemoOrderDate`
FROM `Demo_Orders_M` `DOM`
WHERE (`DOM`.`DemoOrderStatus` = 253)
GROUP BY `DOM`.`CustomerID`
HAVING (COUNT(`DOM`.`CustomerID`) > 1)$$
DELIMITER ;

Mysql trigger variable - find updating user

I have table with fields:
id
data1
data2
next I want to set trigger that after update would write to log table changes:
CREATE TRIGGER `update_data` AFTER UPDATE on `data_table`
FOR EACH ROW
BEGIN
IF (NEW.data1 != OLD.data1) THEN
INSERT INTO data_tracking set old_value = OLD.data1, new_value = NEW.data1, field = "data1";
END IF;
-- similar for data2
END$$
I also want to record in data_tracking table user that made change, however this user is not part of original UPDATE that trigger the trigger. I it a way to let trigger know what user need to be recorded ?
This is PHP based web service with multiple registered users, that can make changes to record via website - those user i would like to add to trigger.
As you want to use the user name that only is known to PHP, well, MySql cannot know which user triggered the change if this information is only available in PHP. This means you would at least have to pass the user in every update statement, either adding this as a column to all tables that need this kind of trigger, or do all the updates via stored procedures that get the user name as an additional parameter. Then you could get rid of all the triggers, as you would use stored procedures anyway that can do the logging as well as the updates.
Use CURRENT_USER, see the MySQL manual: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_current-user

Alternative to block a table

I have a table called 'messages' (INNODB) where the user can insert their own posts.
I want to put a limitation. In my php script when the table gets to 10 records, you can not add more. The logic of the program is more or less as follows.
Step 1. I run a query to count the lines that are in the table.
Step 2. Recovered that value, I decide whether to insert a new post.
My difficulty is in properly managing the possibility of two user who do the same thing simultaneously. If the user A is in step 1 while user B has just finished entering the tenth post, user A will include the eleventh.
How to avoid it?
You can create CHAR(1) NOT NULL field and cover it with UNIQUE INDEX. This will prevent of inserting more than 10 rows.
Other solution that could work would be to create BEFORE INSERT trigger that checks number of rows and raises error if there are more than 10 (look here for sample) (but in this case you can fail with condition races).
In order to allow you to change your threshold value for the table, you can use a trigger. Because MySQL triggers don't have a "prevent INSERT" option, you need a value in your table set to NOT NULL. The trigger can then set the inserted value for that column to NULL which will prevent the INSERT if your condition check fails.
A trigger like this:
CREATE TRIGGER block_insert
BEFORE INSERT ON table_name
FOR EACH ROW
BEGIN
DECLARE count INT;
SELECT COUNT(*)
FROM table_name INTO count;
IF count >= 10
THEN
SET NEW.non_nullable_value = NULL;
END IF;
END;
would fail if you inserted an 11th row, like this:
ERROR 1048 (23000): Column 'non_nullable_value' cannot be null
You may wish to set the non-nullable column's name to something that represents its use. You could improve this by having the trigger pull the limit value from a configuration table.
Update
To avoid having to use the non-nullable columns, you could alternatively create an error procedure, and CALL it from your trigger - similar to the example in the "Emulating Check Constraints" section of this page - they're referencing Oracle databases, where a check constraint achieves what you want, but MySQL doesn't support them.
The "error procedure" in the example performs an INSERT of a duplicate row into an error table, causing a unique key error and stops the parent transaction also.
Update 2
As pointed out in the comment below, multiple simultaneous transactions may get round the checks - you'll have to use LOCK TABLES <name> WRITE in order to ensure that they can't.
2/ You can also lock the MySQL table.
execute : LOCK TABLES my_table
Then do your business rules.
execute : UNLOCK TABLES
This also ensure that each action is sequentially executed. (but you have to deal with performance overhead)
Hope this could be useful.
Updated since the comments below : transaction don't work in this case
1/ You are using InnoDB, you can also use database transaction
Open transaction
Then do your business rules.
Commit or rollback your transaction
This will ensure that each action are executed one after another.

Monitoring MySQL database using PHP

I have a mysql database with 12,000 entries, what i want setup is the ability to monitor a column in the database and if/when the column is altered for any entry it sends me an email with the details.
EDIT: I have access to mysql db, but not the script which works with it. So it should monitor it for changes...
You could create some triggers on the table, if your version of MySQL has them. A trigger can then invoke any function you care to create. A trigger has the advantage that any insertion or deletion or any update of the column will cause it to fire; you wouldn't have to change any other code to make it happen. See here for more... http://dev.mysql.com/doc/refman/5.0/en/triggers.html
Create a trigger on update
Create another table (lets call it cron_table), where the trigger will insert information of the updated row (may be old value, new value etc)
Setup a cron, which will call a script which will check the cron_table and send email if any entry is found. Cron interval can be setup according to need.
--- If you could send email from trigger, there would be no need for a separate table and cron ---
try something similar to this , you can edit the function to send you and email if the query has insert and TABLE_NAME or COLUMN_NAME in it
set up one column to be a datetimestamp.
This will update on every change of the row. There you can run a sql query either via a cron job or after every few php queries to return you the list of changed rows since the last check.
Select * from tbl_myentries where EntryUpdated > '$TimeSinceLastCheck'
you need to understand Data Manipulation Language (DML) triggers
in my sql: use
CREATE TRIGGER salary_trigger
BEFORE UPDATE ON table_name
REFERENCING NEW ROW AS n, OLD ROW AS o
FOR EACH ROW
IF n.columnName <> o.columnname THEN
END IF;
;
Create a trigger on a change on your column, then insert it to another table as log table.
Run cron job on your table that will send you an email.

Categories