Welcome Guest, Not a member yet? Register   Sign In
Getting next ID before insert
#10

[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.


Messages In This Thread
Getting next ID before insert - by El Forum - 06-24-2013, 07:16 AM
Getting next ID before insert - by El Forum - 06-24-2013, 07:44 AM
Getting next ID before insert - by El Forum - 06-24-2013, 11:41 AM
Getting next ID before insert - by El Forum - 06-24-2013, 01:35 PM
Getting next ID before insert - by El Forum - 06-25-2013, 05:29 AM
Getting next ID before insert - by El Forum - 06-25-2013, 05:34 AM
Getting next ID before insert - by El Forum - 06-25-2013, 06:04 AM
Getting next ID before insert - by El Forum - 06-25-2013, 06:23 AM
Getting next ID before insert - by El Forum - 06-25-2013, 06:25 AM
Getting next ID before insert - by El Forum - 06-25-2013, 09:50 AM
Getting next ID before insert - by El Forum - 06-26-2013, 12:10 AM
Getting next ID before insert - by El Forum - 06-26-2013, 06:30 AM



Theme © iAndrew 2016 - Forum software by © MyBB