Ivan
Ivan

Reputation: 5238

Get last insert id return null

I have db table images with primary key ID and auto increment. Am adding new images with ajax > controller > model.

My model for create has method create

  public function create($data = array())
    {
        $this->db->insert($this->_table, $data);

        return $this->db->insert_id();
    }

  public function getLastInserted() {
        return $this->db->insert_id();
  }

And in controller i create test metod to check what is last id inserted:

public function lastID()
{
   var_dump($this->photo->getLastInserted());
}



// int(0)

But record is succeffull inserted in database. What can be problem ?

Upvotes: 1

Views: 2075

Answers (3)

Rakib Roni
Rakib Roni

Reputation: 244

Your create function return last insert id. To see your last insert id just use this code in controller function

public function lastID()
 {
  var_dump($this->photo->create('table_name',$data));
 }

photo model function

function create($tableName, $data)
 {
    $this->db->insert($tableName, $post);
    return $this->db->insert_id();
 }

Upvotes: 0

bigjbomb
bigjbomb

Reputation: 1

lastInsertid only works when you use it on your db connection variable like

dbconnection->lastInsertId()

Upvotes: 0

divix
divix

Reputation: 1374

From the official docs: mysqli::$insert_id - Returns the auto generated id used in the LAST query

Make sure you are not doing any other queries AFTER your create() method.

I would suggest to place a last inserted ID into class variable, to avoid problems like these in the future:

private $lastInsertId = null;

public function create($data = array())
{
    $this->db->insert($this->_table, $data);
    $this->lastInsertId = $this->db->insert_id();

    return $this->lastInsertId;
}

public function getLastInserted() {
    return $this->lastInsertId;
}

Upvotes: 2

Related Questions