I have a SQL databases of users forms, and want to set up some routine or maybe even PHP that will automatically delete empty rows which looks like this:
Column1=(Name=John Surname=Doe) | Column2=(Name=John Surname=) | Column3=(Name=John Surname=Doe)
In this case I would like for database to automatically delete Column2 because surname is missing...
Manually, I could do it like this:
DELETE FROM myTable WHERE Surname='';
Can this be helpful? Never used it.
Or to make some PHP script on load of my website and onload of display of my table (I forgot to mention that I have another web page where I view my table...) which will delete emtpy rows, aka run this code: DELETE FROM myTable WHERE Surname='';
I cannot forbid or put required on my input form because of other reasons...
Any help is apricated, thank You.
First solution:
In Cpanel/DirectAdmin/... create a Cron Job for PHP.
Second solution:
CREATE EVENT IF NOT EXISTS delete_event
ON SCHEDULE EVERY 30 MINUTE
STARTS CURRENT_TIMESTAMP
ENDS CURRENT_TIMESTAMP + INTERVAL 24 HOUR
DO
DELETE FROM myTable WHERE Surname='';
Third solution:
When running the script related to the table, put the delete command.
Add trigger. This will remove the inserted row inmediatly. The new keyword is for access the columns in the inserted row
replace id with the primary key of myTable
DELIMITER $$
CREATE TRIGGER delete_if_empty
AFTER INSERT ON myTable
FOR EACH ROW
BEGIN
IF new.Surname IS NULL OR new.Surname = '' THEN
DELETE FROM myTable WHERE id = new.id;
END IF;
END$$
DELIMITER ;
Another solution could be adding NOT NULL constraint on surname column to prevent insert row like this. Depending on how you handle result of the insert query, probably you will need to add some lines to your code add to avoid breaking of the posterior logic
Related
I have created an event calling a procedure.
My event code:
CREATE EVENT `apelare_stergere` ON SCHEDULE EVERY 2 HOUR_MINUTE STARTS
'2019-07-07 15:57:00.000000' ON COMPLETION PRESERVE ENABLE
DO call stergere_din_rezervari();
My procedure called by the above event:
BEGIN
DELETE FROM rezervari WHERE data_rezervarii < NOW() - INTERVAL 1 DAY;
UPDATE carti SET stoc=stoc+1 WHERE rezervari.idCarte=carti.idCarte;
END
I also have a table called deleted_by_event and would like to save into it all rows from rezervari table what were modified by the procedure.
How can I select all data from rezervari table (reservations) which was modified by the procedure? I want to update a field in a third table also.
Before delete, insert to a ReservationDelete table? Add a column for the carti ID affected
Then to answer your second question, join to the deleted table?
(If other events need to also delete, then add a DeleteSource column to track the source. )
I am quite new to SQL and am working on a small project, but I got stuck when wanting to implement triggers to my model.
I am designing a database for a sports league. I have a table "GamePlayed" with a column called "GoalsScored" and another one "Team" with a column called "GoalsFor". Those two tables are connected by the "TeamID" key.
I would like to have a trigger that updates the value of "GoalsFor" by adding to the previous value the value of "GoalsScored". In this way, with every game, the total quantity of goals scored will be constantly updated.
I tried the following:
CREATE TRIGGER "Goalsscored" AFTER UPDATE
ON `GamePlayed`
FOR EACH ROW
BEGIN
UPDATE `Team` SET `Team`.`GoalsFor`=`Team`.`GoalsFor`+`GamePlayed`.`GoalsScored`
WHERE `GamePlayed`.`Team_TeamID`=`Team`.`TeamID`
END
Unfortunately, it says there is a problem in my SQL syntax...
How can I do it?
You need to change your delimiter. Something like this
delimiter $$
CREATE TRIGGER "Goalsscored" AFTER UPDATE
ON `GamePlayed`
FOR EACH ROW
BEGIN
UPDATE `Team` SET `Team`.`GoalsFor`=`Team`.`GoalsFor`+`GamePlayed`.`GoalsScored`
WHERE `GamePlayed`.`Team_TeamID`=`Team`.`TeamID`;
END;
$$
See eg http://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html
Here is my table
`id` int(11) NOT NULL,
`notifyroles` varchar(50) NULL,
PRIMARY KEY (`id`)
ENGINE=MyISAM DEFAULT CHARSET=utf8
I use it to store a single set of dynamic values of an array that is imploded to string such as item1,item2,item3 and when I pull the data from the db I will explode those values again.
When I initialize my software I insert row id 1 and then leave the notifyroles element as NULL until I used it.
It will and should never have any other rows but row 1 and so I chose not to use the auto increment feature. I never use INSERT I always just use UPDATE for id 1.
Since i dont want to have to write a bunch of code to check for more rows and truncate it and reset it if there is and all of that stuff my question is:
Is there a way to lock the table so that it cannot have more than 1 row? And if someone tried to INSERT another row it would fail.
ps. I am hoping that with the evolution of MySQL that maybe after all this time there is such a way.
Simplest is to manage the rights so the user your software uses has no insert rights but does have update rights on that table.
See: http://dev.mysql.com/doc/refman/5.7/en/grant.html
There's not really a way to lock a table, but you can take advantage of MySQL triggers. As the name suggest, they are activated immediately at the time the specified action is performed, in this case, an insert. Maybe try this:
CREATE TRIGGER locktable
AFTER INSERT ON mytable
FOR EACH ROW
BEGIN
IF (NEW.id != --id of the row you want protected--) THEN
DELETE FROM mytable WHERE id = NEW.id;
END IF;
END;
Why not BEFORE INSERT? some strategies suggest causing the query to fail, but I'm really not comfortable with that approach.
I hope it helps.
I am trying to build a trigger, the problems is it is not working. I have syntax problems. I need to build a trigger which will update a table with another record in the same table before the table has been been updated. The trigger below describes what i want to do but it does not work.
$deletequery = '
DELIMITER //
CREATE TRIGGER after_insert_job_sent
AFTER INSERT
ON Envato_CustomConfig_job_sent FOR EACH ROW
BEGIN
DELETE FROM `Envato_CustomConfig_Job_Queue`
WHERE Job_ID = '.$value['Job_ID'].'
AND email -'.$value['email'].';
UPDATE `envato_customconfig_job_status` SET `email_Sent_Count`= email_Sent_Count+1
WHERE Job_ID = '.$value['Job_ID'].'
END; //
DELIMITER;
insert into Envato_CustomConfig_job_sent
values ( NULL , '.$value['Job_ID'].', '.$value['email'].', now();
';
EDIT:
Why does my query append other records aswell?....
so basically it is working however on the update is add one to the last record the db. i have tried LIMIT it did not work. any ideas.
insert into Envato_CustomConfig_job_sent
values ( NULL , '37', 'email', now());
DELETE FROM Envato_CustomConfig_job_queue
WHERE Job_ID = '37'
AND email ='email';
UPDATE envato_customconfig_job_status SET `email_Sent_Count`= email_Sent_Count+1
WHERE Job_ID = '37';
Triggers, Events, Functions, and Stored Procedures reside as code stored in a particular database. Only some of them have parameter passing (such as Functions and Stored Procedures). Others just fire are their own (Events and Triggers).
What you are attempting to do is perform a delete with PHP variable information which is just a query.
At least you have the DELIMITER concept nailed down, that stands in the way as a trivial error that catches many people. But if you would have highlighted the Trigger block, you would have seen the syntax error highlighting, most likely, around the embedded WHERE Job_ID = '.$value['Job_ID'].' chunk. And since the trigger runs on triggered events such as insert, etc, it would have no clue about that chunk.
When I say highlighted, I mean in a program such as Mysql Workbench.
Let's say I have two tables as shown:
user
id plan course_limit username
10 0 ahmad
note: plan is enum field containing '','a','b','c'.
course
id user_id username
1 10 ahmad
Now I want when a user insert into course as shown I want the course_limit to increment by 1 for that user so that I can apply a limit.
You can create a trigger with the following code.
CREATE
DEFINER = 'root'#'localhost'
TRIGGER databasename.AI_course_each
AFTER INSERT
ON databasename.course
FOR EACH ROW
BEGIN
UPDATE user SET user.course_limit = user.course_limit + 1
WHERE user.user_id = new.user_id;
END;
Some explanation
You create a trigger that fires once for every row FOR EACH ROW that is inserted AFTER INSERT into table course.
When you insert into the table you can trigger BEFORE and AFTER the insert is done.
If you want to be able to prevent the insert you fire before, if you just want to do useful work, you fire after.
The inserted fields can be accessed via a dummy table 'new'.
So here after each insert the UPDATE statement gets executed.
More trigger options
You can also use triggers BEFORE UPDATE, AFTER UPDATE,BEFORE DELETE and AFTER DELETE.
In the update and delete cases you get an extra dummy table old that you can use to refer to the data in the table before the update or delete happened.
Lots more is possible, but I'll keep it simple for now.
See http://forge.mysql.com/wiki/Triggers for more info.
Using a trigger should solve your problem : with that, you'll be able to register SQL code, on your MySQL server, that runs when certain events occur (like insertion).