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

后端 未结 5 860
-上瘾入骨i
-上瘾入骨i 2021-01-13 08:55

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

相关标签:
5条回答
  • 2021-01-13 09:24

    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;
    
    0 讨论(0)
  • 2021-01-13 09:25

    PDO::lastInserId()

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

    0 讨论(0)
  • 2021-01-13 09:29
    SELECT * FROM [tablename] ORDER BY id DESC LIMIT 1
    
    0 讨论(0)
  • 2021-01-13 09:33

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

    SELECT *
    FROM tablename
    WHERE id = (SELECT COUNT(*) FROM tablename);
    
    0 讨论(0)
  • 2021-01-13 09:38

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

    0 讨论(0)
提交回复
热议问题