[英]PDO::lastInsertID returning 0
在閱讀並嘗試了有關該主題的幾乎所有答案之后,lastInsertId仍然返回0。我認為我可能忽略了很明顯的內容,但似乎找不到。
這是我的代碼:
public function create($ordertype, $userid, $travel, $distance, $time, $description, $lineids, $amounts, $descriptions, $prices, $orderid = null) {
try {
$stmt = $this->db->prepare("INSERT INTO workorder(orderid, userid, ordertype, travel, description, distance, totaltime)
VALUES(:orderid, :userid, :ordertype, :travel, :description, :distance, :totaltime)
ON DUPLICATE KEY UPDATE userid=:userid, ordertype=:ordertype, travel=:travel, description=:description,
distance=:distance, totaltime=:totaltime");
$stmt->bindparam(":orderid", $orderid);
$stmt->bindparam(":userid", $userid);
$stmt->bindparam(":ordertype", $ordertype);
$stmt->bindparam(":travel", $travel);
$stmt->bindparam(":description", $description);
$stmt->bindparam(":distance", $distance);
$stmt->bindparam(":totaltime", $time);
$stmt->execute();
$workorderid = $this->db->lastInsertId();
echo $workorderid;
exit();
return $stmt;
save_lines($workorderid, $lineids, $amounts, $descriptions, $prices);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
這很明顯……我忘了檢查記錄是否已經存在。 如果我不更改記錄(工作單)中的任何內容,則SQL查詢不執行任何操作,並且lastInsertId
返回0
。
我更新的代碼(首先檢查orderid
ID是否有ID):
public function create($ordertype, $userid, $travel, $distance, $time, $description, $lineids, $amounts, $descriptions, $prices, $orderid = null) {
try {
$stmt = $this->db->prepare("INSERT INTO workorder(orderid, userid, ordertype, travel, description, distance, totaltime)
VALUES(:orderid, :userid, :ordertype, :travel, :description, :distance, :totaltime)
ON DUPLICATE KEY UPDATE userid=:userid, ordertype=:ordertype, travel=:travel, description=:description,
distance=:distance, totaltime=:totaltime");
$stmt->bindparam(":orderid", $orderid);
$stmt->bindparam(":userid", $userid);
$stmt->bindparam(":ordertype", $ordertype);
$stmt->bindparam(":travel", $travel);
$stmt->bindparam(":description", $description);
$stmt->bindparam(":distance", $distance);
$stmt->bindparam(":totaltime", $time);
$stmt->execute();
if($orderid == null) {
$workorderid = $this->db->lastInsertId();
} else {
$workorderid = $orderid;
}
if($amounts !== '') {
$this->save_lines($workorderid, $lineids, $amounts, $descriptions, $prices);
}
} catch(PDOException $e) {
echo $e->getMessage();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.