问题描述
我正在尝试写入两个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中选择vehicle_id。
- 我的insert语句将如何将数据写入表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程序,这是一种造成巨大混乱(竞赛条件)的臭名昭著的方法。