Skip to content

PDO (mysql) unexpected lastInsertId when primary key is negative number #8746

@jtuta

Description

@jtuta

Description

The following code:

<?php
$dbh = new PDO('mysql:host=mysql;dbname=database', 'user', 'pass');
    $dbh->prepare("CREATE TABLE `Datatable` (`id` int NOT NULL, `value` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
ALTER TABLE `Datatable` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `id` (`id`);
ALTER TABLE `Datatable` MODIFY `id` int NOT NULL AUTO_INCREMENT;")->execute();
    $stmt = $dbh->prepare("insert into `Datatable` (`value`, `id`) values (?, ?)");
    $stmt->execute( array('test', -1));
    var_dump(
        $dbh->lastInsertId(),
        $dbh->query("SELECT * FROM `Datatable`")->fetch()
    );

Resulted in this output:

string(20) "18446744073709551615" array(4) { ["id"]=> int(-1) [0]=> int(-1) ["value"]=> string(4) "test" [1]=> string(4) "test" }

But I expected this output instead:

string(20) "-1" array(4) { ["id"]=> int(-1) [0]=> int(-1) ["value"]=> string(4) "test" [1]=> string(4) "test" }

Example has been run in docker image:

  • php:8.1-fpm
  • mysql image (if relevant) mysql:8.0.27

I

PHP Version

PHP 8.1.7

Operating System

Ubuntu 22.04

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions