Reputation: 6763
How can I generate a progressive sequential unique id in PHP?
For example, the order should be this:
aaaaaa < aaaaab < aaaaac etc...
Upvotes: 3
Views: 9314
Reputation: 4401
If you use any of the other solutions here, you'll still have to fetch or save the last id and then increment it. Instead, you could simply use the auto-incremented id and convert it into a textual representation.
I'm using Laravel examples here, but you can apply the theory to any framework.
// Save your model.
$flight = new Flight;
$flight->name = $request->name;
$flight->save();
// $flight->id now contains the last inserted id.
echo base_convert($flight->id, 10, 36);
// Output: 1E86
Base 10 is numbers from 0-9. Base 36 adds the 26 letters of the alphabet to that.
Note that there is no need to actually save the output back to the database, which would take another query and defeat the purpose of this optimisation. Instead, you can add a mutator that converts the id in real time:
class Flight extends Model {
...
public function getUniqueIdAttribute()
{
return base_convert($this->id, 10, 36);
}
}
Now you can simply save your model and call $flight->uniqueId
and get your base 36 converted id.
Tip: Add a salt value to the id to prevent leaking actual database ids.
Upvotes: 0
Reputation: 95101
This is by default in PHP Incrementing/Decrementing Operators
can work directly with Strings please see http://php.net/manual/en/language.operators.increment.php
$start = "aaaaaa" ;
$start++;
$start++;
var_dump($start);
Output
string 'aaaaac' (length=6)
Upvotes: 6
Reputation: 31813
$id = 'aaaax';
for ($i=0; $i<100; $i++) {
$id++;
echo "$id\n";
}
demo http://codepad.org/ogGrOfyQ
Upvotes: 1
Reputation: 324620
uniqid()
is increasing (an ID generated later will always be greater than one generated earlier) but will not be sequential (there will be gaps).
Otherwise, find a way to save the last generated ID, and increment it when you generate a new one.
Upvotes: 8