I've come across with a problem. My framework was working just fine with PHP 5.3.0. I upgraded my PHP version to PHP 5.4.x and I started to have few issues with some parts of my framework.
After PHP version upgrade, PDO lastInsterId()
always returns 0
.
I have auto-increment field called id
.
It is adding the data to database without any problems.
For some reason I keep getting 0 as last insert id.
Here is my code;
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);
}
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 (:
static
keyword in your method definitions. How are you calling these methods? – Stereotaxisdatabaseobjects.php
. This way, I don't repeat myself while coding. – YeastylastInsertId()
is unique to the connection, not the table - are you executing any other DB queries between callingcreate()
andlastInsertID()
? Also note thatlastInsertId()
reports0
if the queries are executed within a transaction and you query the id afterCOMMIT
– CallboyINSERT
query ran just before runninglastInsertID()
method. I also triedreturn $db->handler->lastInsertId('id');
without any success. – Yeasty