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

[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!
#2

[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);
    }
  }
}
#3

[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!
#4

[eluser]Colin Williams[/eluser]
http://ellislab.com/codeigniter/user-gui...lpers.html




Theme © iAndrew 2016 - Forum software by © MyBB