How to solve this problem (mysql table): What PHP code or MySQL that I need to use (when I delete adminid = 1 from table A, the value of adminid table B should change to 0)
? Is it possible?
Table A has:
adminid = 1
adminname = jack
Table B has:
newsid = 1
adminid = 1
The TableB.adminid
should change to 0
if TableA.adminid = 1
gets deleted.
Thanks!
Through PHP and MySql it's possible if the adminid is not a foreign key in table B (In relationship with table A). Instead of 0 you can make it to null using mysql. There is a SQL command you need to use to enable it: ON DELETE SET NULL
.
Refer this for more detail
You can use MySQL triggers to set the desired value for table_b.adminid
when table_a.adminid
is changed. You can create your own functions and procedures as well in the triggers to set desired value on conditions.
For e.g.
CREATE TABLE table_a (adminid INT, adminname VARCHAR(255));
CREATE TABLE table_b (newsid INT, adminid INT);
CREATE TRIGGER delete_adminid AFTER DELETE ON table_a
FOR EACH ROW
BEGIN
UPDATE table_b SET adminid = 0 WHERE adminid = OLD.adminid;
END;
The above trigger will set table_b.adminid = 0
after any delete action on table_a
.
Using triggers you do not need to write any back-end code. Every change is handled by database server. Also, you can write triggers before/after INSERT
, UPDATE
actions as well.
References: