[英]Inserting to multiple mysql table based on an primary key from first table
I am trying to write to two mysql tables.我正在尝试写入两个 mysql 表。
Table 1: vehicles
表 1: vehicles
-----------------------------------------------------------------
| vehicle_id | vehicle_name | vehicle_type | status |
-----------------------------------------------------------------
The field vehicle_id
is auto incremented.字段vehicle_id
是自动递增的。 I need to use this field in the next table speed_log
.我需要在下一个表speed_log
使用这个字段。
This is the other table that.这是另一个表。
Table 2: speed_log
表 2: speed_log
--------------------------------------
| id | vehicle_id | speed |
--------------------------------------
As above, the id
is auto incremented but I need to pick the vehicle_id
from the first table when the script runs.如上所述, id
是自动递增的,但我需要在脚本运行时从第一个表中选择vehicle_id
。 The vehicle_id
in the second table is the foreign key.第二个表中的vehicle_id
是外键。
This is my syntax for writing data to the table 1这是我将数据写入表 1 的语法
//query
$query = "INSERT INTO vehicles SET vehicle_name=:vehicle_name, vehicle_type=:vehicle_type, status=:status";
//prepare query
$stmt = $this->conn->prepare($query);
// bind values
$stmt->bindParam(":vehicle_name", $this->vehicle_name);
$stmt->bindParam(":vehicle_type", $this->vehicle_type);
$stmt->bindParam(":status", $this->status);
// execute query
if($stmt->execute()) {
$this->response_message = "Vehicle was registered successfully.";
return true;
}
else {
$this->response_message = "Unable to register vehicle ".json_encode($stmt->errorInfo()).".";
}
return false;
Now my issues are two:现在我的问题有两个:
This is a job for LAST_INSERT_ID()
or its PDO variant.这是LAST_INSERT_ID()
或其 PDO 变体的工作。
Do something like this做这样的事情
// execute query
if($stmt->execute()) {
$this->response_message = "Vehicle was registered successfully.";
$vehicleId = $this->conn->lastInsertID();
/* now do another INSERT to your second table using the value of `$vehicleId`. */
return true;
}
Whatever you do, do not do anything like无论你做什么,都不要做类似的事情
SELECT 1 + MAX(vehicle_id) FROM vehicles; /* wrong! */
because that is a notorious way of making a huge mess (race conditions) if more than one user is using your php program concurrently.因为如果有多个用户同时使用您的 php 程序,这是一种臭名昭著的方式,会造成巨大的混乱(竞争条件)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.