I\'m trying to fetch the last inserted row Id of a Sqlite DB in my PHP application. I\'m using Zend Framework\'s PDO Sqlite adapter for database handling. the lastInsertId()
Do not use
SELECT * FROM tablename WHERE id = (SELECT COUNT(*) FROM tablename);
instead use
SELECT MAX(id) as id FROM tablename LIMIT 1;
or
SELECT id FROM tablename ORDER DESC LIMIT 1;
PDO::lastInserId()
see: http://us2.php.net/manual/en/pdo.lastinsertid.php
SELECT * FROM [tablename] ORDER BY id DESC LIMIT 1
Hey, try this query. But I don't know about PHP.
SELECT *
FROM tablename
WHERE id = (SELECT COUNT(*) FROM tablename);
Given an SQLite3 Database with a table b
, as follows:
BEGIN TRANSACTION;
CREATE TABLE b(a integer primary key autoincrement, b varchar(1));
COMMIT;
This code gives me a lastInsertId
:
public function lastInsertId() {
$result = $this->_connection->query('SELECT last_insert_rowid() as last_insert_rowid')->fetch();
return $result['last_insert_rowid'];
}
That is - if your table is defined correctly, your only problem is likely to be that you tried to fetch key $result[0] - also, whenever you're using a computed column, I recommend aliasing the column using the "AS" keyword as I've demonstrated above. If you don't want to alias the column, in SQLite3 the column should be named "last_insert_rowid()".