Synchronization of Phpmyadmin tables

Asked

Viewed 137 times

0

I needed help in PHP My Admin on synchronizing fields in different tables and in the same database.
For example:

Database: Data Base Test
Table test1
columns:
- col1
- col2

Table test2
columns:
- col1
- col3

It needed that, when values were inserted in table 1, table 2 would have column 3 null and columns 1 equal.


Note: I use PHP My Admin version 4.7.4

1 answer

0


You can use a TRIGGER for this, see below:

Table1:

CREATE TABLE Teste1(
   ID INT AUTO_INCREMENT PRIMARY KEY,
   Nome NVARCHAR(30) NOT NULL
);

Table 2:

CREATE TABLE Teste2(
   Teste1ID INT PRIMARY KEY,
   Algumacoisa NVARCHAR(50) DEFAULT NULL,

   CONSTRAINT FK_Teste1_em_Teste2
   FOREIGN KEY (Teste1ID)
   REFERENCES Teste1.ID
);

Trigger used to insert new record after an INSERT in Table1:

CREATE TRIGGER Gatilho_Teste1
AFTER INSERT
ON Teste1 FOR EACH ROW
INSERT INTO Teste2(Teste1ID) VALUES(NEW.ID);

See Working: inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

After each record is inserted in Table 1 Trigger is fired and inserts msm id in table 2, already in column 3 you requested null, so only declare the DEFAULT NULL in the construction of the table.

  • Hello I was testing this solution and I could not put in phpmyadmin this trigger. It says there’s a mistake next to AS on line 4 and gives errors in creating tables via console. Could help me with phpmyadmin?

  • @Simplecoder went badly and for the delay, to update, I found 2 problems in my answer that have already been healed. 1º had an extra comma in the first table. 2º o AS in TRIGGER I believe I typed on impulse. It does not answer before because it was turning on the community by app and had no way to test. But it’s all right now.

  • Thanks, this worked more or less the way you indicated. I still haven’t been able to create the table teste2 using SQL code, but created using the wizard and did not need to define a foreign key.

  • @Simplecoder is working correctly, I honestly do not know what you are doing there is not be that post the error print. The Foreign Key serves to verify and guarantee the referential integrity of the table. A reason for it not working may be the ENGINE.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.