本文介绍了如何使用两个表在mysql db中插入新记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题.我创建了两个表kontrola"和naruszenie".在 kontrola 表中,我与 'naruszenie' 表有外键关系.当我想显示属于 'kontrola' 表的所有记录时,我使用这个:

I have a little problem. I've create a two tables 'kontrola' and 'naruszenie'. In kontrola table I have a foreign key relation to 'naruszenie' table. When I want to display all records belong to 'kontrola' table I use this:

$listakontroli = $connecting->query("SELECT k.id, k.podmiot, k.miasto, k.wszczeto, k.zakonczono, n.naruszenie FROM kontrola k INNER JOIN naruszenia n ON k.naruszenie_id=n.id");

一切正常.如何使用这 2 个表创建查询 INSERT TO 以添加新记录?

And everything working properly.How to create a query INSERT TO to add the new record using this 2 tables?

现在我有这样的查询但不起作用

Now I have query like this but doesn't work

$dodajKontrole = "INSERT INTO kontrola (podmiot, miasto, wszczeto, zakonczono, naruszenie_id) VALUES ('$nowyPodmiot', '$noweMiasto', '$datawszczecia', '$datazakonczenia', '$nowenaruszenie')";

推荐答案

如果你想在 mySQL 级别上做,请尝试使用 mysql TRIGGER

Try to use a mysql TRIGGER if you want to do it in mySQL level

  CREATE TRIGGER insert_into_naruszenia AFTER INSERT ON `kontrola`
  FOR EACH ROW
  BEGIN
     INSERT INTO naruszenia (naruszenie) VALUES (NEW.id)
  END;

  INSERT INTO kontrola (....) VALUES (....);

我没有测试过,但应该可以.

I didn't test it but is should do the job.

如果您想在 php 代码中使用它,您始终可以使用 LAST_INSERT_ID().

If you want to use it inside php code you always have the LAST_INSERT_ID() that you can use.

  INSERT INTO kontrola (....) VALUES (....);
  INSERT INTO naruszenie (id) VALUES (LAST_INSERT_ID());

这篇关于如何使用两个表在mysql db中插入新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 09:49