简体   繁体   English

PDO lastInsertID返回0

[英]PDO lastInsertID is returning 0

I am having trouble with lastInsertID returning 0. It is working in another page, so I have something wrong here. 我在lastInsertID返回0时遇到麻烦。它正在另一页中工作,所以这里有些问题。

The following is in a try/catch block. 以下是try / catch块中的内容。

$idCount = "42";
/** set the database **/
$db = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
/** set the error reporting attribute **/
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);            
$stmt = $db->prepare("SELECT image1 FROM items WHERE `id` = :id");    
/** bind the parameters **/
$stmt->bindParam(':id', $idCount, PDO::PARAM_STR);   
$stmt->execute();                 
$idCount = $db->lastInsertId();
echo $idCount;

lastInsertId() will only return the last insert id if you actually do an insert. 如果您实际执行插入操作, lastInsertId()将仅返回最后一个插入ID。 You are only doing a select . 您仅在进行select

The function name ->lastInsertId() should give you a hint that SELECT statements wouldn't normally set the last insert id. 函数名称->lastInsertId()应该提示您SELECT语句通常不会设置最后的插入ID。

Typically only INSERT statements on tables with an auto_increment column exhibit that behaviour. 通常,只有具有auto_increment列的表上的INSERT语句才会显示该行为。

There are exceptions though, such as when LAST_INSERT_ID(expr) is used: 但是有一些例外,例如使用LAST_INSERT_ID(expr)

SELECT LAST_INSERT_ID(`id`) AS `id`, image1 FROM items WHERE `id` = :id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM