CodeIgniter Forums
Getting next ID before insert - 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: Getting next ID before insert (/showthread.php?tid=58560)

Pages: 1 2


Getting next ID before insert - El Forum - 06-24-2013

[eluser]Felipe Deitos[/eluser]
I Know that this is a newbie and old question, but i need to know the next id on a table so i can give the images that i am uploading the name of that id.

Code:
$this->db->insert_id(); // this can be called but i need to get it before the insert

Any clue?
Sorry about my english by the way...

Cheers


Getting next ID before insert - El Forum - 06-24-2013

[eluser]Felipe Deitos[/eluser]
I was thinking, maybe the best thing to do is insert the $data first and then upload the images, and if theres is a problem inserting the images i can delete the row using the $this->db->insert_id();?

What you guys think about it, what is the right and the best thing to do?

Cheers!


Getting next ID before insert - El Forum - 06-24-2013

[eluser]sotoz[/eluser]
You can do the insert to the database, get the last inserted id with db->insert_id and then rename your uploaded image file to your last_inserted_id.jpg

Then when you need to show this record's image you can echo its id+.jpg for the img src.

If you need code for that tell me and I can write something for you.


Getting next ID before insert - El Forum - 06-24-2013

[eluser]Ckirk[/eluser]
how about:
Code:
// users table for example
$query = $this->db->query('SELECT id FROM users ORDER BY id DESC LIMIT 1');
if ($query->num_rows() > 0)
{
  $user = $query->result();
  $next_id = $user[0]->id + 1;
}



Getting next ID before insert - El Forum - 06-25-2013

[eluser]Felipe Deitos[/eluser]
Ckirk: I guess this is wrong, example: if your last recorded id is 570 but u got the 571 and 572 deleted the next id would be 573, but in your code it will be 571.

Sotoz: Thats what i am doing i wrote some functions yesterday and make it work really great, take a look:
Code:
function create(){
  
  $info = array(
   'idcategoria' => $this->input->post('ipt_categoria'),
   'codigo' => $this->input->post('ipt_codigo'),
   'nome' => $this->input->post('ipt_nome'),
   'descricao' => $this->input->post('ipt_descricao'),
   'esp_tecnica' => $this->input->post('ipt_esp_tecnica'),
   'ativo' => $this->input->post('ipt_ativo'),
   'destaque' => $this->input->post('ipt_destaque')
  );
  
  
  $query = $this->db->insert('produtos', $info);
  //Could make one if $query
  $insert_id = $this->db->insert_id();
  
  $files = $_FILES;
  $erros = array();
  $imagens = array();
  foreach($files as $field => $file){
   if(!empty($file['name'])){
    $upload = $this->upload_imagem($insert_id, $field); //upload image function
    if(isset($upload['error'])){
     $erros[$field] = $upload['error'];
    }else{
     $imagens[$field] = $upload['imagem'];
    }
   }
  }
  
  if(!empty($erros)){
   foreach($erros as $key => $erro){
   // doing it now, there are 5 images so if the 4 give anything wrong i delete the others and delete the record too.
   }
  }else{
   $this->db->where('id', $insert_id);
   $this->db->update('produtos', $imagens);
  }
}

Thanks for the answers guys, really appreciated!

Cheers!


Getting next ID before insert - El Forum - 06-25-2013

[eluser]Ckirk[/eluser]
Yep I would never do what I suggested for that very reason, but without more I couldn't see what you were trying to do with it.
Glad you got it sorted though Smile


Getting next ID before insert - El Forum - 06-25-2013

[eluser]Pert[/eluser]
Another option is to save image files with temporary random unique filename, if there are no errors, create DB record and then rename files to use new ID.

If thumbnail generations fails, you won't end up pushing ID higher and higher, but that's probably just personal preference Smile

Depending on the images, it would also be easy for someone to scroll through all the images by just changing ID number on URL.



Getting next ID before insert - El Forum - 06-25-2013

[eluser]Felipe Deitos[/eluser]
Pert: That was a nice option, now i got the code done, but next time i will try your way, because i really dont like the idea of the ID going Higher and Higher.

Normally i dont put the id on the name of the image, but i got this job already done, and i am updating it to CI and trying to follow the same thing it was before because there are over 2000 products and i dont wanna change it hehe.

Again, appreciated for your answers!

Cheers!


Getting next ID before insert - El Forum - 06-25-2013

[eluser]Pert[/eluser]
Not to worry, just pointing out things that have become issues over time for my own projects Smile


Getting next ID before insert - El Forum - 06-25-2013

[eluser]bazianm[/eluser]
I hope you don't mind a relative CI newbie getting involved here but I have solved this problem differently.

I don't use sequential, integer IDs. I haven't for years. I use UUIDs for that purpose. Here's what I do:

I subclasses CI_Controller and added a method called _newid(). I searched the net for code that generates a uuid() (I could've just gotten it from MySQL but I didn't want the round trip) and put it into that method. Here's the code (again, this isn't mine)...

Code:
function _newid() {
     return sprintf( 'xx-x-x-x-xxx',
       // 32 bits for "time_low"
       mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
    
       // 16 bits for "time_mid"
       mt_rand( 0, 0xffff ),
    
       // 16 bits for "time_hi_and_version",
       // four most significant bits holds version number 4
       mt_rand( 0, 0x0fff ) | 0x4000,
    
       // 16 bits, 8 bits for "clk_seq_hi_res",
       // 8 bits for "clk_seq_low",
       // two most significant bits holds zero and one for variant DCE1.1
       mt_rand( 0, 0x3fff ) | 0x8000,
    
       // 48 bits for "node"
       mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
     );
    }

My controllers are defined based on MY_Controller so they pick up the method. Once I have this, the rest is simple. Just pull out a _newid() and put it where you like and use it all over the place.

I like UUIDs for a few reasons:

1) If I have to merge two databases, I do not have to worry
2) I do not care about what ID is next... it's random.

I ran a routine that generated something like 100,000 of those newids to see if I got a dupe and I didn't.