Welcome Guest, Not a member yet? Register   Sign In
Generating Unique ID
#9

[eluser]Michael Wales[/eluser]
It was unclear you were referring to looping and checking against the database result to ensure the value was unique. What I thought you meant was:

Code:
$moreUnique = md5(uniqid(rand(), true));
$this->db->insert('table', array('code' => substr($moreUnique, 5)));

Which, simply wouldn't work - for very apparent reasons. In case you aren't catching on:

uniqid() will generate a random, unique, 13-character string. See that? 13 characters...

Let's simplify things a bit, so we're all following along.

mike_uniqid() will generate a unique string that is 3 characters long, digits only. So, we run it and get 014. Now, we substring that down to 2 characters and we have 01.

What happens when we insert that into the database and the next guy comes along and receives 018 for his random string. DING DING DING! The database tries to insert 01, the app pukes, and fail whale gives you a sweet little visit.

Now, back to your recommendation:
uniqid() - no matter how many times you feel like hashing, seeding, etc. generates a random string. Let's say it's: u0sduf0duf9832jhewhj0fjew9f7ud

We substring it down to u0sdu and insert.

Now, fail whale decides to visit our little web app and he gets the random string: u0sduf003kz832jh93hj0fjewlsnud

We substring it... and well, I guess you can see where I am going with this.

So, the conclusion of today's lesson folks:
1. Yes, Randy's solution is better because it doesn't include the loading of a library.
2. You would still have to combine it with the while() loop I explained to ensure a random string is actually being entered into the database.
3. Randy's a smartass and I hope I never have to clean up one of his apps, especially if he thinks a substring of a unique string will result in a unique string.


Messages In This Thread
Generating Unique ID - by El Forum - 07-06-2008, 11:14 AM
Generating Unique ID - by El Forum - 07-06-2008, 11:23 AM
Generating Unique ID - by El Forum - 07-06-2008, 12:59 PM
Generating Unique ID - by El Forum - 07-06-2008, 04:11 PM
Generating Unique ID - by El Forum - 07-06-2008, 04:19 PM
Generating Unique ID - by El Forum - 07-06-2008, 04:30 PM
Generating Unique ID - by El Forum - 07-06-2008, 06:07 PM
Generating Unique ID - by El Forum - 07-06-2008, 06:23 PM
Generating Unique ID - by El Forum - 07-06-2008, 07:32 PM
Generating Unique ID - by El Forum - 07-06-2008, 08:41 PM
Generating Unique ID - by El Forum - 07-06-2008, 10:18 PM
Generating Unique ID - by El Forum - 07-06-2008, 10:35 PM
Generating Unique ID - by El Forum - 07-06-2008, 11:48 PM
Generating Unique ID - by El Forum - 07-07-2008, 12:27 AM
Generating Unique ID - by El Forum - 07-07-2008, 12:53 AM
Generating Unique ID - by El Forum - 07-07-2008, 01:07 AM



Theme © iAndrew 2016 - Forum software by © MyBB