【问题标题】:how to get sequence id of last inserted record in oracle 11g xe with php?如何使用 php 在 oracle 11g xe 中获取最后插入记录的序列 ID?
【发布时间】:2013-07-28 06:23:47
【问题描述】:

我在这里尝试插入一条记录并检索最后插入的序列 id,但没有成功,谁能帮助我,指导我 oracle 如何与 php 一起工作?

$query = 'INSERT INTO hist_news (id,headline,reportedon,reportedby,loc,story,more,helperjson,refjson,createdt,createdby) VALUES(id.nextval, :headline, :reportedon, :reportedby , :loc , :story , :more , :helper , :ref , sysdate , :createdby) return id.nextval';
        $this->stmt = oci_parse($this->oci,$query);
        oci_bind_by_name($this->stmt,':headline',$headline);
        oci_bind_by_name($this->stmt,':reportedon',$reportedon);
        oci_bind_by_name($this->stmt,':reportedby',$reportedby);
        oci_bind_by_name($this->stmt,':loc',$loc);
        oci_bind_by_name($this->stmt,':story',$story);
        oci_bind_by_name($this->stmt,':more',$more);
        oci_bind_by_name($this->stmt,':helper',$helperjson);
        oci_bind_by_name($this->stmt,':ref',$refjson);
        if($re = oci_execute($this->stmt)){
            return $re;
        } else {
            return false;
        }

【问题讨论】:

    标签: php sql plsql oracle11g


    【解决方案1】:

    在插入语句之后可以执行select id.currval from dual。这应该给你最新的价值。请注意,这仅在您获取 nextval 后在当前会话中有效,并且不能单独使用。

    【讨论】:

    • 它总是返回 1 if(oci_execute($this->stmt)){ $this->stmt = oci_parse($this->oci,'select id.currval from dual'); return oci_execute($this->stmt); }
    • 我对 PHP 不太熟悉,但我猜你看到的是执行语句的状态码。您必须执行select id.currval into :loc_variable from dual 然后检查 loc_variable 的值。
    • thanx @verma 我错过了 fetch 语句。
    • @Verma 如果同时从序列中提取的另一个值比序列的当前值增加,则可能导致获取错误的值。
    • @harshit 因为 currval 取决于会话,所以这可能不是问题。但是,我建议彻底测试以确保行为符合预期。
    【解决方案2】:

    将以下内容添加到您的插入 SQL 查询中:

    returning id into :id
    

    例子:

    $query = 'INSERT INTO hist_news (id,headline,reportedon,reportedby,loc,story,more,helperjson,refjson,createdt,createdby) VALUES(id.nextval, :headline, :reportedon, :reportedby , :loc , :story , :more , :helper , :ref , sysdate , :createdby) returning id into :id';
    

    并将其绑定到您的语句

    oci_bind_by_name($this->stmt,":ID",$id);
    

    现在$id 将在oci_execute($this->stmt) 执行后拥有最后插入的ID;

    此方法适用于 OCI8。

    【讨论】:

    • 2 个关于 ORACLE 和 PHP 的注释。在@kavehmb 的回答中,有些人可能没有注意到,但该字段是id,但他在绑定方法上使用:ID - 对我来说,Oracle 正在将所有内容都转换为大写,所以请注意这一点。此外,对于其他类型的字段,Oracle 驱动程序似乎需要知道您想从返回变量中获取多少个字符。我通过添加 32 作为绑定的最后一个参数来实现此功能:oci_bind_by_name($stmt, ':MYFIELD', $myField, 32);。希望它可以帮助别人!
    猜你喜欢
    • 2011-06-24
    • 2011-03-09
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    • 2016-11-25
    • 1970-01-01
    相关资源
    最近更新 更多