Gman
Gman

Reputation: 783

How do I use uniqid to generate a 6 chars length ID?

My website has a section that generates a unique id for every post and then it's sent to the database. The problem is that the ID that is generated totals 16 chars in length and I need the id to be 6 chars only.

This is the code that is used to generate the ID:

$order_id  = uniqid(rand(10,1000), false);

Is there any way that I could accomplish such a change?

Upvotes: 3

Views: 12903

Answers (2)

Ruslan Skaldin
Ruslan Skaldin

Reputation: 1091

As OptimusCrime said above you can use auto_increment in the database, with PHP function str_pad. For example:

<?php

$input = 5;
echo str_pad($input, 6, "0", STR_PAD_LEFT);

Code above will generate 6 digit string, so you can play with function to gain string whatever you want:

000005

Upvotes: 0

OptimusCrime
OptimusCrime

Reputation: 14863

Why not do this with auto_incremental in the database? So the first id is 1, then 2 and so on. If you only need 6 digits this will result in 999 999 different keys.


The previously accepted answer here, using substr() to take the first 6 characters from uniqid(), is not 100% safe. uniqid will product a unique id where the WHOLE id will be unique. By removing these characters you may end up with duplicates.

Upvotes: 20

Related Questions