Md. Nazmul Hosan
Md. Nazmul Hosan

Reputation: 97

codeigniter oracle get insert_id()

Working in CodeIgniter with Oracle database. Now the problem is $this->db->insert_id(); is not working here though it works perfectly in MySQL DB. The error report is:

A Database Error Occurred

This feature is not available for the database you are using.

Filename: D:\xampp\htdocs\spiceram\system\database\drivers\oci8\oci8_driver.php

Line Number: 503

how can i get the last insert id;

Upvotes: 0

Views: 3672

Answers (3)

Bablu Ahmed
Bablu Ahmed

Reputation: 5010

Try like this:

public function save($table, $data)
{
    $res = $this->db->insert($table, $data);

    //First select id attribute name
    $query = $this->db->get($table);
    $row = array_keys($query->row_array());
    $id_attr = $row[0];

    //Last Inserted id
    if($res)
    {
        $query2 = $this->db->query("select MAX($id_attr) from $table");
        $row2 = array_values($query2->row_array());
        $id = $row2[0];
        return $id;
    }
    else
    {
        return false;
    }
}

OR

function insert($tableName, $post)
    {
        //First insert data
        $res = $this->db->insert($tableName, $post);

        //Get inserted id
        if($res){
            $row = $this->db->query("SELECT ID FROM $tableName ORDER BY ID DESC OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY")->row();
            $id = $row->ID;
            return $id;
        }else{
            return false;
        }

    }

Upvotes: 1

Alaa Krunb
Alaa Krunb

Reputation: 9

you can use this cod, it's code return ID.

public function new_req($emp_id, $dep_id, $note)
{
    $query = $this->db->query('SELECT MAX(REQ_ID)+1 as ID FROM REQ');
    $row = $query->row();
    $id = $row->ID;

    if($id == NULL) $id = 1; 

    $data["REQ_ID"]   =$id;
    $data["EMP_ID"]   =$emp_id;
    $data["DEP_ID"]      =$dep_id; 
    $data["REQ_TYPE"]   =1;
    $data["REQ_NOTE"]   =$note;
    $data["IP"]           =$_SERVER['REMOTE_ADDR'];

    $this->db->insert("REQ",$data);
    return $id;
}

Upvotes: 1

Nirjhor Anjum
Nirjhor Anjum

Reputation: 1

private function insert() {
  $this->ID = $this->getNextId();
  $this->db->insert($this->getTableName(), $this);
  $this->log($this->ID);
}
private function getNextId() {
  $this->db->select($this->getTableName()."_SEQUENCE.NEXTVAL AS NEXTID", FALSE);
  $this->db->from("dual");
  $query = $this->db->get();
  $row = $query->row();
  return $row->NEXTID;
} 

Hope this should solve the issue for case of Oracle Database.

Upvotes: 0

Related Questions