Php 基于第一个表中的主键插入多个mysql表

Php 基于第一个表中的主键插入多个mysql表,php,mysql,foreign-keys,Php,Mysql,Foreign Keys,我正在尝试写入两个mysql表 表1:车辆 ----------------------------------------------------------------- | vehicle_id | vehicle_name | vehicle_type | status | ----------------------------------------------------------------- 字段车辆id自动递增。我需要在下一个表中使用此字段speed\u

我正在尝试写入两个mysql表

表1:
车辆

-----------------------------------------------------------------
|  vehicle_id  |  vehicle_name  | vehicle_type  |  status  | 
-----------------------------------------------------------------
字段
车辆id
自动递增。我需要在下一个表中使用此字段
speed\u log

这是另一张桌子

表2:
speed\u log

 --------------------------------------
 |  id  |  vehicle_id  | speed  |
 --------------------------------------
如上所述,
id
是自动递增的,但我需要在脚本运行时从第一个表中选择
vehicle\u id
。第二个表中的
车辆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中选择车辆id
  • 我的insert语句如何将数据写入表2
  • 这是针对或其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程序,这是一种臭名昭著的制造混乱(竞争条件)的方式。

    为什么不使用mysql触发器?