2 回答

TA贡献1851条经验 获得超4个赞
正如评论中提到并随后要求的那样 - 一个trigger似乎是处理问题的好选择,因为您只需要关心初始插入 - 然后触发器会自动处理重复的 ID(或其他字段)。
给定两个基本表来从问题中复制这些
mysql> describe employees;
+----------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(50) | NO | | 0 | |
| position | varchar(50) | NO | | 0 | |
| salary | decimal(10,2) | NO | | 0.00 | |
+----------+------------------+------+-----+---------+----------------+
mysql> describe date;
+-----------+------------------+------+-----+-------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+------------------+------+-----+-------------------+-------+
| id | int(10) unsigned | NO | PRI | NULL | |
| timestamp | timestamp | NO | | CURRENT_TIMESTAMP | |
+-----------+------------------+------+-----+-------------------+-------+
一个简单trigger的绑定到表并在添加新行时employees插入到表中。date
CREATE TRIGGER `tr_employee_inserts` AFTER INSERT ON `employees` FOR EACH ROW BEGIN
insert into `date` set `id`=new.id;
END
去测试
insert into employees (`name`,`position`,`salary` ) values ( 'Peter', 'Porcupine Pickler', 75000 );
insert into employees (`name`,`position`,`salary` ) values ( 'Roger', 'Rabitt Rustler', 25000 );
insert into employees (`name`,`position`,`salary` ) values ( 'Michael', 'Mouse Mauler', 15000 );
select * from `employees`;
select * from `date`;
结果
mysql> select * from employees;
+----+---------+-------------------+----------+
| id | name | position | salary |
+----+---------+-------------------+----------+
| 1 | Peter | Porcupine Pickler | 75000.00 |
| 2 | Roger | Rabitt Rustler | 25000.00 |
| 3 | Michael | Mouse Mauler | 15000.00 |
+----+---------+-------------------+----------+
mysql> select * from date;
+----+---------------------+
| id | timestamp |
+----+---------------------+
| 1 | 2020-01-16 10:11:15 |
| 2 | 2020-01-16 10:11:15 |
| 3 | 2020-01-16 10:11:15 |
+----+---------------------+

TA贡献1807条经验 获得超9个赞
用于$last_id = $con->insert_id;获取最后插入的 ID。
请尝试以下代码。它为你工作。
$field1 = 'name';
$field2 = 'position';
$field3 = '10000';
$field4 = 'SOF01';
// insert employees data
$stmt = $con->prepare("INSERT INTO employees (name,position,salary,empid) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $field1, $field2, $field3, $field4);
$stmt->execute();
// get last insert id
$last_id = $con->insert_id;
// insert last id in date table
$stmt = $con->prepare("INSERT INTO date (id) VALUES (?)");
$stmt->bind_param("s", $last_id);
$stmt->execute();
- 2 回答
- 0 关注
- 156 浏览
添加回答
举报