簡體   English   中英

根據第一個表中的主鍵插入到多個 mysql 表

[英]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;

現在我的問題有兩個:

  1. 我應該如何從表 1 中選擇 Vehicle_id。
  2. 我的插入語句將如何將數據寫入表 2

這是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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM