CodeIgniter Forums
Returning the Primary Key when inserting a record - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Returning the Primary Key when inserting a record (/showthread.php?tid=14982)



Returning the Primary Key when inserting a record - El Forum - 01-22-2009

[eluser]juddmuir[/eluser]
Hi,

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?

Thanks!


Returning the Primary Key when inserting a record - El Forum - 01-22-2009

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

Your model:
Code:
class Post extends Model {

  var $last_id;

  function Post() {
    parent::Model();
  }

  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:
Code:
class Posts extends Controller {

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



Returning the Primary Key when inserting a record - El Forum - 01-22-2009

[eluser]juddmuir[/eluser]
Aha, that's what I was looking for:

$this->db->insert_id();

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


Returning the Primary Key when inserting a record - El Forum - 01-22-2009

[eluser]Colin Williams[/eluser]
http://ellislab.com/codeigniter/user-guide/database/helpers.html