例如,我有两个数据库:
客户表(id是自动增加的)
---------------------------------------
----- id ----- name ----- surname -----
----- 1 ----- BOB ----- test1 -----
----- 2 ----- Jhon ----- test2 -----
----- 3 ----- Nick ----- test3 -----
---------------------------------------和产品表(id不是null,必须手动添加)
---------------------------------------------
----- id ----- product ----- date -----
----- 1 ----- orange ----- 10/10/2014 -----
----- 2 ----- apple ----- 12/10/2014 -----
----- 3 ----- melon ----- 26/10/2014 -----
---------------------------------------------*我有一个更复杂、更大的桌子。
问题是:
使用一个add.php文件来添加
姓名= ____姓氏= _____
在从添加名称和姓氏的字段(从表客户)获取id之后,使用它使用相同的id添加产品和日期(到product表)。
我了解如何向多个表添加信息:这里
但是,如何向表1中添加信息,在使用table1添加tables2的ID之后,这就是我感到困惑的地方。
发布于 2014-11-01 12:58:59
使用mysql_insert_id();,它为您提供上一次查询的id
http://php.net/manual/en/function.mysql-insert-id.php
来自php.net的示例
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>因此,首先执行第一个查询,使用mysql_insert_id()获取id,然后编写第二个查询。
发布于 2014-11-01 13:06:34
若要插入第一行,请正常使用此查询。
INSERT INTO customer (name, surname)
VALUES ('Marie', 'Antoinette')它将为连接设置LAST_INSERT_ID()值。然后,要插入下一行,请使用此查询,它包含LAST_INSERT_ID()。
INSERT INTO product (customer_id, product, date)
VALUES (LAST_INSERT_ID(), 'Cake', '1770-04-18')这允许您在不显式检索LAST_INSERT_ID的情况下执行第二个插入。但是,如果一个客户有多个product行,那么您需要在SQL中做一些稍微不同的事情。
INSERT INTO customer (name, surname)
VALUES ('Marie', 'Antoinette');
SET @custid =: LAST_INSERT_ID();
INSERT INTO product (customer_id, product, date)
VALUES (@custid, 'Cake', '1770-04-18')
INSERT INTO product (customer_id, product, date)
VALUES (@custid, 'Guillotine', '1770-04-19')这是一种很好的方法,因为它可以在一个繁忙的系统上正常工作,在这个系统中,可能会有多个数据库客户端插入客户。LAST_INSERT_ID()由MySQL逐个连接维护.这也很好,因为您不必检索最后插入的id值,然后将其发回。
https://stackoverflow.com/questions/26689386
复制相似问题