Welcome Guest, Not a member yet? Register   Sign In
How to get id after insert data
#6

[eluser]darkhouse[/eluser]
Just adding my 2 cents. I once had an application (not code igniter, this is like 5 years ago) give me a terrible problem where I had 2 people register at the exact same time. I was returning mysql_insert_id() but it returned the same id to both of them. Since I was doing stuff with the id after the user had registered, it really screwed things up, which I had to go in and fix manually.

I still use $this->db->insert_id() as I think that occurrence was a 1-in-a-million fluke, but the solution I had to use, and still sometimes use today even though it's a little more taxing, is to run a select right after the insert to grab the proper id. Something like this:

Code:
//users_model.php
function insert_user($username, $password, $email){
   $data = array(
      'username' => $username,
      'password' => $password,
      'email' => $email
   );
   $this->db->insert('users', $data);

   foreach($data as $key => $val){
      $this->db->where($key, $val);
   }
   $this->db->order_by('date_joined', 'desc'); //date_joined is a TIMESTAMP, default CURRENT_TIMESTAMP
   $query = $this->db->get('users', 1);
   return $query->row()->id;
}

I don't know if that will ever help anyone, just sharing one of my more memorable experiences, and a possible solution in case it ever happens to anyone.

Ever since that day, a pipe dream of mine has always been that it would be nice if running an INSERT query would return the primary key for that new record. Then you could just do $id = mysql_query("INSERT INTO..."); return $id; Or if it was an optional paramater, like $id = mysql_query("INSERT INTO...", $link, TRUE); ... anyways, I'm rambling. Pipe dream.


Messages In This Thread
How to get id after insert data - by El Forum - 07-19-2009, 02:39 AM
How to get id after insert data - by El Forum - 07-19-2009, 03:19 AM
How to get id after insert data - by El Forum - 07-19-2009, 04:11 AM
How to get id after insert data - by El Forum - 07-19-2009, 04:56 AM
How to get id after insert data - by El Forum - 07-19-2009, 06:39 AM
How to get id after insert data - by El Forum - 07-19-2009, 10:05 AM
How to get id after insert data - by El Forum - 07-19-2009, 11:32 AM
How to get id after insert data - by El Forum - 07-19-2009, 11:42 AM
How to get id after insert data - by El Forum - 09-11-2010, 02:21 PM
How to get id after insert data - by El Forum - 09-11-2010, 02:52 PM
How to get id after insert data - by El Forum - 09-11-2010, 03:26 PM
How to get id after insert data - by El Forum - 09-11-2010, 03:29 PM
How to get id after insert data - by El Forum - 09-12-2010, 02:09 AM
How to get id after insert data - by El Forum - 09-12-2010, 04:20 AM



Theme © iAndrew 2016 - Forum software by © MyBB