Write a recursive function that tests $reference_no
if it exists, elaborate next one (003, ...) by recalling your function
if not, create it and end your function
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
So i have a database which has contact_name and also referenc_no.
So when i save a fresh contact into the database it auto assigns the reference number by taking the first 4 letters from the name and add 001 to the back.
$name = 'John Doe';
$number = 1;
$justname = explode(' ', $name);
$firstname = $justname[0];
$reference_no = strtoupper(substr($firstname, 0, 4)) . str_pad($number, 3, '0', STR_PAD_LEFT);
E.G Contact name is John Doe so reference number is JOHN001.
But i want to know how i can write a code that checks if the name John exists in the database and add 002 to it and also 003 if another user with the name John exists.
The below code checks if the any record has the name John in it and adds 002 behind it
$jah = $contact_name;
$just = App::sql()->query_row("SELECT * FROM customer WHERE contact_name = '$jah'" );
$final = explode(' ', $jah);
$justfinal = $final[0];
if($justfinal == $firstname){
$name = explode(' ', $contact_name);
$majorname = $name[0];
$ref = 1;
$ref++;
$reference_no = strtoupper(substr($majorname, 0,4)). str_pad($ref, 3, '0', STR_PAD_LEFT);
}
The above code checks and adds 002 but if another record with john exists it does not add 003 it adds 002
Please or to participate in this conversation.