I am having trouble with lastInsertID returning 0. It is working in another page, so I have something wrong here.
The following is in a try/catch block.
$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. You are only doing a select
.
The function name ->lastInsertId()
should give you a hint that SELECT statements wouldn't normally set the last insert id.
Typically only INSERT statements on tables with an auto_increment
column exhibit that behaviour.
There are exceptions though, such as when LAST_INSERT_ID(expr)
is used:
SELECT LAST_INSERT_ID(`id`) AS `id`, image1 FROM items WHERE `id` = :id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.