阅读并尝试几乎关于此主题的每个答案后,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();
}
}
答案 0 :(得分:-1)
显而易见......
我忘了检查记录是否已经存在。如果我没有更改记录(工作订单)中的任何内容,则SQL查询没有执行任何操作,lastInsertId
返回0
。
我的更新代码(首先检查orderid
是否为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();
}
}