how to get last inserted Id of a Sqlite database using Zend_Db

耗尽温柔 提交于 2019-12-30 09:40:09

问题


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() method is supposed to give me the results, but it wouldn't. In PDO documentation in php.net I read that the lastInsertId() might not work the same on all databases. but wouldn't it work on sqlite at all? I tried overwriting the lastInsertId() method of the adapter by this:

// Zend_Db_Adapter_Pdo_Sqlite
public function lastInsertId() {
    $result = $this->_connection->query('SELECT last_insert_rowid()')->fetch();
    return $result[0];
}

but it does not work either. just returns 0 everytime I call it. is there any special clean way to find the last inserted Id?


回答1:


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()".




回答2:


PDO::lastInserId()

see: http://us2.php.net/manual/en/pdo.lastinsertid.php




回答3:


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;



回答4:


SELECT * FROM [tablename] ORDER BY id DESC LIMIT 1



回答5:


Hey, try this query. But I don't know about PHP.

SELECT *
FROM tablename
WHERE id = (SELECT COUNT(*) FROM tablename);


来源:https://stackoverflow.com/questions/506132/how-to-get-last-inserted-id-of-a-sqlite-database-using-zend-db

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!