PDO::lastInsertID 返回 0
Posted
技术标签:
【中文标题】PDO::lastInsertID 返回 0【英文标题】:PDO::lastInsertID returning 0 【发布时间】:2016-02-11 13:29:28 【问题描述】:在阅读并尝试了有关此主题的几乎所有答案后,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();
【问题讨论】:
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES,TRUE);准备前使用 插入数据库是工作还是不工作? 当我添加$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES,TRUE);
时,它可以工作。
@devpro 请解释一下?我很想知道为什么在运行->execute()
之前推迟编译查询会使之前没有的工作。正如我认为它默认为 TRUE 反正
默认情况下它已经是 TRUE - 所以它不应该影响任何东西。看起来你不小心修正了一个错字。
【参考方案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();
【讨论】:
以上是关于PDO::lastInsertID 返回 0的主要内容,如果未能解决你的问题,请参考以下文章