繁体   English   中英

[PHP][MySQL] 如何同时在2个表中插入数据?

[英][PHP][MySQL] How to insert data in 2 tables at same time?

我在 2 个表中插入数据时遇到了一些问题,需要一些帮助。

例如:

表格1:

CREATE TABLE tb1 (
    tb1_id int(5) not null AUTO_INCREMENT PRIMARY KEY,
    tb1_title varchar(50),
    tb1_cat varchar(50)
);

表 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)
);

tb1一个条目可以有tb2许多信息(行),但是如何在tb2某些行中插入tb1的 id 呢?

公式.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);

我在这里需要改变什么?

您可以使用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);
}

是的,你可以..试试这个..

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM