让codeigniter的oci8 db driver支持insert_id()

来自http://tunps.com/codeigniter-oci8-insert_id-implementation

php_mysql模块有一个函数:mysql_insert_id

功能是

mysql_insert_id() 返回给定的 link_identifier 中上一步 INSERT 查询中产生的 AUTO_INCREMENT 的 ID 号。如果没有指定 link_identifier ,则使用上一个打开的连接。

说白了就是返回上一次insert的id号,但是oracle没有auto_increment属性,不能让字段自增,一般业内的解决方法是用sequence+trigger方案。今天需要取得oracle insert之后的id值,直接用上了codeigniter的$this->db->insert_id(),结果codeigniter报错提示:This feature is not available for the database you are using。我表示鸭梨很大,到底有好大?鸭梨山大:

/**
* Insert ID
*
* @access public
* @return integer
*/
function insert_id()
{
// not supported in oracle
return $this->display_error('db_unsupported_function');
}


既然都display_error了还返回的是interger。- -#
没办法codeigniter支持的数据库是主流的mysql,oracle是被抛弃的小孩。我们只能自己将其抚养成人了。
insert_id代码修改为:

function insert_id($tbl='')
{
$sql = "select " . $tbl . "_seq.currval as id from dual";
$statement = @ociparse($this->conn_id, $sql);
$row=@ociexecute($statement);
@ocifetchinto($statement, $row, OCI_ASSOC);
return $row['ID'];
}


加了一个$tbl参数,因为必须要传递$tbl,才能知道要查询的sequence,而且sequence要有一定的命名规范,比如:tablename_seq。

About tunpishuang

just 4 fun·····
This entry was posted in 未分类 and tagged , . Bookmark the permalink.

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>