[英][PHP][MySQL] How to insert data in 2 tables at same time?
I have a little problem to insert data in 2 tables and need some help with it.我在 2 个表中插入数据时遇到了一些问题,需要一些帮助。
For example:例如:
Table 1:表格1:
CREATE TABLE tb1 (
tb1_id int(5) not null AUTO_INCREMENT PRIMARY KEY,
tb1_title varchar(50),
tb1_cat varchar(50)
);
Table 2:表 2:
CREATE TABLE tb2 (
tb2_id int(5) not null AUTO_INCREMENT PRIMARY KEY,
tb2_title varchar(50),
tb2_doc varchar(200),
id_tb1 int(5) not null REFERENCES tb1(tb1_id)
);
One entry of tb1
can have many information(rows) of tb2
, but how to insert the id of tb1
in some rows of tb2
? tb1
一个条目可以有tb2
许多信息(行),但是如何在tb2
某些行中插入tb1
的 id 呢?
formular.php:公式.php:
$sqla = "INSERT INTO tb_1 (tb1_title, tb1_cat) VALUES ('$tb1_title', '$tb1_cat')";
$sqlb = "INSERT INTO tb_2 (tb2_title, tb2_doc, <b>[? ? ?]</b>) VALUES ('$tb2_title', '$tb2_doc', <b>[? ? ?]</b>)";
mysqli_query($db, $sqla);
mysqli_query($db, $sqlb);
What do I have to change here?我在这里需要改变什么?
You can get the value of tb1_id
using mysqli_insert_id()
, and then insert that into tb2
:您可以使用mysqli_insert_id()
获取tb1_id
的值,然后将其插入tb2
:
$sqla = "INSERT INTO tb1 (tb1_title, tb1_cat) VALUES ('$tb1_title', '$tb1_cat')";
if (mysqli_query($db, $sqla)) {
$tb1_id = mysqli_insert_id($db);
$sqlb = "INSERT INTO tb2 (tb2_title, tb2_doc, id_tb1) VALUES ('$tb2_title', '$tb2_doc', $tb1_id)";
mysqli_query($db, $sqlb);
}
Yes you can.. try this..是的,你可以..试试这个..
BEGIN;
INSERT INTO tb_1 (tb1_title, tb1_cat) VALUES ('$tb1_title', '$tb1_cat');
INSERT INTO tb_2 (tb2_title, tb2_doc, <b>[? ? ?]</b>,id_tb1) VALUES ('$tb2_title', '$tb2_doc', <b>[? ? ?]</b>,LAST_INSERT_ID());
COMMIT;
$sqla = "INSERT INTO tableA (col1, col2) VALUES (val1, val2)";
mysqli_query($db,$sqla);
$id = mysqli_insert_id($db); //add it here.
$sqlb = "INSERT INTO tableB (col1,col2) VALUES (val1, val2, ...)";
//then you can pass the id into your second query
//...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.