Welcome Guest, Not a member yet? Register   Sign In
Returning the Primary Key when inserting a record


I'm using
$this->db->insert('table_name', $data);

I then want to save some images uploaded at the same time, using the primary key of the inserted record as the folder name.

What's best practice for getting hold of the Primary Key after inserting a record?


[eluser]Michael Wales[/eluser]
Use a class variable within your model to store the Unique ID on a successful insertion.

Your model:
class Post extends Model {

  var $last_id;

  function Post() {

  function save($post = array()) {
    if (count($post) > 0) {
      $query = $this->db->insert('posts', $post);
      if ($query->affected_rows() > 0) {
        $this->last_id = $this->db->insert_id();
        return TRUE;
  return FALSE;

Your Controller:
class Posts extends Controller {

  function index() {
    // Generate your data to be inserted
    if ($this->post->save($post)) {
      // Now we'll save our images, based on the unique ID
      $image['post_id'] = $this->post->last_id;

Aha, that's what I was looking for:


Not documented as far as I can see, and very useful! Thanks for the reply!

[eluser]Colin Williams[/eluser]

Theme © iAndrew 2016 - Forum software by © MyBB