I’m generating a random 10 character string with php, and inserting it into a column in my DB. My issue is that I want this string to be unique(in the database). I’ve thought of many ways of doing this, but wondering which way is the most efficient.
My PHP looks like this(random string can only be 10 chars long):
//generates an almost unique(not quite) ticket number
$pretrimmedtask = md5(uniqid(mt_rand(),true));
$tasknum = substr($pretrimmedtask ,0,10);
I then take this “unique” value and insert it. But because of the trim of the string, this value is by no means unique. I’m wondering what is the best way of making sure this value could never be duplicated, while still being efficient.
(I understand that querying the db to look for this value in there is possible… but I would rather do it in a more elegant fashion)
You should update your table and make the relevant column be a
UNIQUE KEY, than try to insert the generated string, if no rows where inserted, generate another key and try again.The code below will try to
INSERTa new row intotable1, if unable it will try again with a different random generated$key.IE. the query will not succeed if
col2has a unique key constraint and the value of$keyalready exists in the column.You can of course use your own algorithm for generating random strings.
NOTE: Make sure that the query can potentially succeed so that you don’t get caught in an endless loop.