Reputation: 379
I connect up to my DB and a user submit their email address. This is stored in the DB. This is something I have grabbed from a turorial.
I'd like a user-unique code generated through JS on document load.. Format should be 6 digits in length and only using only A-Z and 0-9. ie: F4DRB6
Once that is done I'd need to store that unique code for that user in the DB.
The generator should check if the unique code exists in the DB, to ensure it is actually unique.
The trouble I am having is; I don't know how to create the unique code in the above format, checking if it is unique from the DB, and then storing it in the DB corresponding to that user. I'd assume another column to match the row somehow?
Thanks!
EDIT: I have attempted with this.. if there is any error please do point it out. Thanks
function genRandomString() {
$length = 5;
$characters = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$string = '';
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
do {
$random_string = $this->genRandomString();
} while (mysql_num_rows(mysql_query("SELECT referralcode FROM ".coming_soon_emails." WHERE rand_string='{$random_string}'")));
$q = "INSERT INTO ".coming_soon_emails." SET referralcode='{$random_string}'";
$result = mysql_query($q);
Upvotes: 0
Views: 3898
Reputation: 895
In a causal way, a simple walk-through would be:
write a function/SP in mysql :
First, generate a random code, as AbiusX said, depends on your user pool size, the new code is probably rarely used.
This will generate one Hex character for you and should get you started.
SELECT conv(FLOOR((RAND() * 16)),10,16);
Then you will need to check if this code has been used already. `
SELECT * FROM usertable where code = generatedcode
if so, generate a new one.
In a more robust setting, I always pre-generate the unique codes, and store them in a table "unused code" etc, so I can just grab any code off there and ensure it is unique and not used.
Upvotes: 0
Reputation: 10580
why you need that to be created in client-side? Why can't you just create the code when the client submits the "final" form?
You can create this code randomly and you put the column that handles the code as unique
. If you get a violation error, you generate another and try again.
Well, this is one of the ways to do...
Upvotes: 3
Reputation: 2404
Its simple math, 6^36 is large enough that creating a random id is mostly unique.
If you wanna be 100% sure use AJAX to check the generated ID in database and recreate if existing.
Upvotes: -1