[英]How to update two mySQL tables and input primary key from first table into second table?
[英]Inserting to multiple mysql table based on an primary key from first table
我正在嘗試寫入兩個 mysql 表。
表 1: vehicles
-----------------------------------------------------------------
| vehicle_id | vehicle_name | vehicle_type | status |
-----------------------------------------------------------------
字段vehicle_id
是自動遞增的。 我需要在下一個表speed_log
使用這個字段。
這是另一個表。
表 2: speed_log
--------------------------------------
| id | vehicle_id | speed |
--------------------------------------
如上所述, id
是自動遞增的,但我需要在腳本運行時從第一個表中選擇vehicle_id
。 第二個表中的vehicle_id
是外鍵。
這是我將數據寫入表 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;
現在我的問題有兩個:
這是LAST_INSERT_ID()
或其 PDO 變體的工作。
做這樣的事情
// 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;
}
無論你做什么,都不要做類似的事情
SELECT 1 + MAX(vehicle_id) FROM vehicles; /* wrong! */
因為如果有多個用戶同時使用您的 php 程序,這是一種臭名昭著的方式,會造成巨大的混亂(競爭條件)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.