Context and goal
In table clients
I have a column clientNum CHAR(11) NOT NULL
with UNIQUE KEY
constraint. It contains client number in the format xxx-xxx-xxx
where x
is a decimal digit. For more details on the format see below.
I want to implement something like AUTO_INCREMENT
for this column so that each client gets their number calculated automatically. From MySQL CREATE TABLE
docs:
An integer or floating-point column can have the additional attribute
AUTO_INCREMENT
. When you insert a value ofNULL
(recommended) or0
into an indexedAUTO_INCREMENT
column, the column is set to the next sequence value. Typically this isvalue+1
, wherevalue
is the largest value for the column currently in the table.AUTO_INCREMENT
sequences begin with1
.
So I want to find the next number available and use it as clientNum
value for newly inserted client row. Next number available is current maximum of clientNum
incremented.
I’m coding in PHP using PDO to access the MySQL database (see PDO Tutorial for MySQL Developers).
Client number format
As stated above, the client number is in format xxx-xxx-xxx
where x
is a decimal digit. The range of each segment is 000
to 999
. It is basically a 9-digit integer with leading zeroes and dash as thousands separator. It cannot get above 999-999-999
.
Currently we want it be even more restricted, specifically in format 000-1xx-xxx
(between 000-100-000
and 000-199-999
). But there are already some numbers in the database that can start anywhere from 000-000-001
to 500-000-000
.
Unfortunately it has to be stored in this format, I cannot change it.
Finding maximum
I need to get the max number in range 000-100-000
to 000-199-999
, values outside this range must be ignored. This is where my problem comes in because as said before some numbers already exist above this.
Maximum is never 000-199-999
. Otherwise in would result in adding 000-200-000
and the next time called maximum will be 000-199-999
again, resulting in attempt to insert 000-200-000
again.
How incrementation works
In PHP in can be done like this:
$clientNum = "000-100-000";
$clientNum = str_replace("-", "", $clientNum);
$clientNum++;
$clientNum = implode("-", str_split(str_pad($clientNum, 9, "0", STR_PAD_LEFT), 3));
Final $clientNum
value is 000-100-001
.
When the initial number is 000-120-015
then the code above produces 000-120-016
. Overflow propagates to the next segment, i.e. 000-100-999
becomes 000-101-000
. 999-999-999
cannot be incremented.
Idea to start with
In a loop I want to get the next number available, check if that number exists in the database, and if so, redo that loop until it finds an unused number. I know how to check if it’s in the database the first time, but I’m not sure how to do the loop.
Does anyone know a way to do this?