使用php DB类插入后,从Oracle获取自动生成的id

时间:2013-12-04 16:14:13

标签: php oracle class oop model

所以我有一个意大利面条PHP应用程序,我正在转换为使用OOP数据库类/ MVC布局

以前,在表单上,​​有一个sql语句正在post上执行,它会将插入的ID提取到绑定变量中(基于SO Get the auto-generated ID after an insert

$sql ="insert into table (name, type) values (:name, :type) returning id into :id";
$squery = oci_parse($link, $sql);
  oci_bind_by_name($squery,":name", $_POST['name']);  
  oci_bind_by_name($squery,":type", $_POST['type']);
  oci_bind_by_name($squery,":id", $id,-1, SQLT_INT);
oci_execute($squery);

此时,可以使用$ id,因为已为变量分配了插入的ID

所以,这是我的问题,我的模型将值从$ _POST传递到数据库类,但从不指定变量

模型

function create(){

$sql ="insert into table (name, type) values (:name, :type) returning id into :id";
 $this->db->execute($sql, "table insert", 
 array(
   array(":name", $_POST['name'], -1, SQLT_CHR),
   array(":type", $_POST['type'], -1, SQLT_CHR),
   array(":id", $id,-1, SQLT_INT)
        )
    );
 return $id;
}

数据库类(基于http://docs.oracle.com/cd/E17781_01/appdev.112/e18555/ch_three_db_access_class.htm

public function execute($sql, $action, $bindvars = array()) {
    $this->stid = oci_parse($this->conn, $sql);
    if ($this->prefetch >= 0) {
        oci_set_prefetch($this->stid, $this->prefetch);
    }
    foreach ($bindvars as $bv) {
        // oci_bind_by_name(resource, bv_name, php_variable, length , type)
        oci_bind_by_name($this->stid, $bv[0], $bv[1], $bv[2], $bv[3]);
    }
    oci_set_action($this->conn, $action);
    oci_execute($this->stid);              // will auto commit

}

该类是正确的,这意味着它将执行正常,它不会返回最后插入的id。

1 个答案:

答案 0 :(得分:0)

这就是我想出来的(当然这是一个更好的答案)

问题是当我传入变量返回bind时,它没有将变量作为变量($ id)传递它作为变量值传递它,并且它没有被分配所以它是空白的< / p>

所以在我创建的数据库类中

public function executeAndReturnID($sql, $action, $bindvars = array(), $return) {
    $this->stid = oci_parse($this->conn, $sql);
    if ($this->prefetch >= 0) {
        oci_set_prefetch($this->stid, $this->prefetch);
    }
    foreach ($bindvars as $bv) {

        oci_bind_by_name($this->stid, $bv[0], $bv[1], $bv[2], $bv[3]);
    }
    // THIS PART TAKES THE RETURN AND CREATES A BIND AND VARIABLE
    oci_bind_by_name($this->stid, ':'.$return, $res, -1, SQLT_INT);

    oci_execute($this->stid);              // will auto commit
    $this->stid = null;  // free the statement resource
    return($res);   

    }

并在我的模型中

function create(){

$sql ="insert into table (name, type) values (:name, :type) returning id into :id";
 $id = $this->db->executeAndReturnID($sql, "table insert", 
 array(
   array(":name", $_POST['name'], -1, SQLT_CHR),
   array(":type", $_POST['type'], -1, SQLT_CHR),

        ),
   "id" //the bind var for return into
    );
 return $id;
}