Hi I am working in a shopping database with php. For this I need to create a Id ( automatically) for each product when I add a new item in to the database and I am using php.
I want to create that id automatically and without repetition. It can be 5-10 letters length.

Please help me

Rajeesh

I would really discourage this - use an autoincrement integer (or mediumint - depending on the max no. of products that you envisage your database holding). I image that you are using a database model with primary/foreign key relationships (indexing). Text indexing is slooooooow. If your proposed text primary key is randomly generated, it would have no bearing on the identification of the product (ie no relationship to the name of the product), so I can't see the rationale behind this. However, I'm no major expert.

hi thanks for support .. Actually I just want a value like this "54856xcvc" Please help me

And I had a code like this...

$string = md5(microtime() * mktime());
$id = substr($string,0,6);

Will it cause repetition in any condition ????

If you were using the full MD5 hash then there would be a small chance for repition, however since you are only using the first 6 characters, this chance is greater.

You must the uniqe product ID be in the format you suggest? Would it not make more sense to have an 'id' column which is an auto-increment and also have a 'product_id' where you can put your fancy ID without fear of having duplicates.

If you really wanted to you could then index the product_id column and seacrh it, but this would not be the best idea as the IDs may not be unique..

Try using time(), it produces a number value that is different every second and would never repeat. You could also add a rand() command to add a random number on the end so even if two people created a product at exactly the same time there would be a slim chance that it would be the same;

$ID = time() . rand(0,9); //Unix Time & A random number between 0 and 9

if you wanted to be almost certain not to create any duplicates you could increase the second number in the rand() command

Hope this helps,
Regards,
Sam Rudge

This article has been dead for over six months. Start a new discussion instead.