如何使用 Zend_Db 获取最后插入的 Sqlite 数据库的 ID [英] how to get last inserted Id of a Sqlite database using Zend_Db

查看:33
本文介绍了如何使用 Zend_Db 获取最后插入的 Sqlite 数据库的 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的 PHP 应用程序中获取 Sqlite 数据库的最后插入的行 ID.我正在使用 Zend Framework 的 PDO Sqlite 适配器进行数据库处理.lastInsertId() 方法应该给我结果,但它不会.在 php.net 的 PDO 文档中,我读到 lastInsertId() 在所有数据库上的工作方式可能不同.但它根本不适用于 sqlite 吗?我尝试通过以下方式覆盖适配器的 lastInsertId() 方法:

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];
}

但它也不起作用.每次我调用它时只返回 0.有没有什么特别干净的方法可以找到最后插入的Id?

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?

推荐答案

给定一个带有表b的SQLite3数据库,如下:

Given an SQLite3 Database with a table b, as follows:

BEGIN TRANSACTION;
CREATE TABLE b(a integer primary key autoincrement, b varchar(1));
COMMIT;

这段代码给了我一个lastInsertId:

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

也就是说 - 如果您的表定义正确,您唯一的问题可能是您试图获取键 $result[0] - 此外,每当您使用计算列时,我建议使用正如我在上面演示的那样,AS"关键字.如果您不想为该列设置别名,则在 SQLite3 中,该列应命名为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()".

这篇关于如何使用 Zend_Db 获取最后插入的 Sqlite 数据库的 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆