PDO lastInsertId() always return 0

Asked
Active3 hr before
Viewed126 times

7 Answers

always
90%

When no exception is thrown, lastInsertId returns 0. However, if lastInsertId is called before calling commit, the right id is returned.,After you commit a transaction PDO::lastInsertID() will return 0, so best to call this method before the transaction is committed. , Stack Overflow Public questions & answers ,After PHP version upgrade, PDO lastInsterId() always returns 0.

You can test PDO to make sure that part is working correctly with this code (in a new file):

// Replace the database connection information, username and password with your own.
$conn = new PDO('mysql:dbname=test;host=127.0.0.1', 'user', 'password');

$conn - > exec('CREATE TABLE testIncrement '.
   '(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50))');
$sth = $conn - > prepare('INSERT INTO testIncrement (name) VALUES (:name)');
$sth - > execute([':name' => 'foo']);
var_dump($conn - > lastInsertId());
$conn - > exec('DROP TABLE testIncrement');
load more v
88%

You can test PDO to make sure that part is working correctly with this code (in a new file):,$this->dbh->lastInsertId(); ,First create() method is called, then crudQuery() method is called. As I mentioned before, I can add the data successfully to MySQL database. Unfortunately when I call lastInsterID() method, it always returns 0.,I will be really glad if you can help me out with this problem before I will get the last ID with SQL Query (:

databaseobjects.php

public static
function create() {
   global $db;
   $attributes = self::sanitize(static::$fields);

   $sql = "INSERT INTO ".PREFIX.static::$table_name.
   " (";
   $sql. = join(", ", array_keys($attributes));
   $sql. = ") VALUE (:";
   $sql. = join(", :", array_keys($attributes));
   $sql. = ")";

   return ($db - > crudQuery($sql, $attributes)) ? true : false;
}

public static
function lastInsertID() {
   global $db;
   return $db - > handler - > lastInsertId();
}

database.php

public
function crudQuery($sql, $data) {
   $sth = $this - > handler - > prepare($sql);
   return $sth - > execute($data);
}
load more v
72%

PDO::lastInsertId — Returns the ID of the last inserted row or sequence value , lastInsertId , If a sequence name was not specified for the name parameter, PDO::lastInsertId() returns a string representing the row ID of the last row that was inserted into the database. , If a sequence name was specified for the name parameter, PDO::lastInsertId() returns a string representing the last value retrieved from the specified sequence object.

load more v
65%

If I try the same with a native PDO query it works, but not with the CakePHP QueryBuilder.,The result of lastInsertId() is always "0".,After every SELECT the lastInsertId() is 0. That's the reason.,I've tried it. The new row is inserted but the lastInsertId is still "0".

CREATE TABLE `users`(
   `id`
   INT NOT NULL AUTO_INCREMENT,
   `username`
   VARCHAR(255),
   PRIMARY KEY(`id`)
) ENGINE = INNODB CHARSET = utf8 COLLATE = utf8_unicode_ci;
load more v
75%

I am using PDO in MySQL to insert a ticket. I want to return the ticket number which is the primary key (auto increment) but it's always returning zero.,The questions is what sp_add_new_ticket does. Does it even use auto increment?,For example, this does not use auto increment,If you're committing after every statement (i.e., you're not explicitly beginning a transaction), then you have no chance to get the ID.

here is the code I am using:

$mysql_query = $mysql_connection - > prepare("CALL sp_add_new_ticket(:param_ticket_name, :param_ticket_email, :param_ticket_subject, :param_ticket_message)");
// $mysql_connection->beginTransaction();
$mysql_query - > bindParam(':param_ticket_name', $ticket_name, PDO::PARAM_STR);
$mysql_query - > bindParam(':param_ticket_email', $ticket_email, PDO::PARAM_STR);
$mysql_query - > bindParam(':param_ticket_subject', $ticket_subject, PDO::PARAM_STR);
$mysql_query - > bindParam(':param_ticket_message', $ticket_message, PDO::PARAM_STR);

$mysql_query - > execute();

$ticket_number = $mysql_connection - > lastInsertId();
load more v
40%

You may often find the need to get the auto incremented ID value for a row that you have just inserted into your database table. You can achieve this with the lastInsertId() method., PDO::lastInsertId() , PDO::lastInsertId() ,In postgresql and oracle, there is the RETURNING Keyword, which returns the specified columns of the currently inserted / modified rows. Here example for inserting one entry:

You may often find the need to get the auto incremented ID value for a row that you have just inserted into your database table. You can achieve this with the lastInsertId() method.

// 1. Basic connection opening (for MySQL)
$host = 'localhost';
$database = 'foo';
$user = 'root'
$password = '';
$dsn = "mysql:host=$host;dbname=$database;charset=utf8";
$pdo = new PDO($dsn, $user, $password);

// 2. Inserting an entry in the hypothetical table 'foo_user'
$query = "INSERT INTO foo_user(pseudo, email) VALUES ('anonymous', 'anonymous@example.com')";
$query_success = $pdo - > query($query);

// 3. Retrieving the last inserted id
$id = $pdo - > lastInsertId(); // return value is an integer
load more v
22%

Returns the identifier for the row most recently inserted into a table in the database. The table must have an IDENTITY NOT NULL column. If a sequence name is provided, lastInsertId returns the most recently inserted sequence number for the provided sequence name (for more information about sequence numbers, see here).,If no sequence name is provided, a string of the identifier for the row most recently added. If a sequence name is provided, a string of the identifier for the sequence most recently added. If the method call fails, empty string is returned.,Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.,$name: An optional string that lets you specify a sequence name.

Syntax

  string PDO::lastInsertId([$name = NULL]);
load more v

Other "always-undefined" queries related to "PDO lastInsertId() always return 0"