Firstly, I apologize if this was asked earlier - indeed, I am sure that it is, but I canโt find it / I canโt decide what to look for, to find it.
I need to create a unique quick link identifier based on the company name. For example:
Company name reference
Smiths Joinery smit0001
Smith and Jones Consulting smit0002
Smithsons Carpets smit0003
All of them will be stored in the varchar column in the MySQL table. Data will be collected, shielded and inserted as "HTML โ PHP โ MySQL". The identifier should be in the format indicated above, four letters, then four digits (initially at least - when I reach smit9999 , it just goes 5 digits).
I can handle the creation of 4 letters from the company name, I just go through that name until I type 4 alpha characters, and strtolower() is - but then I need to get the next available number.
What is the best / easiest way to do this to eliminate the possibility of duplication?
At the moment, I think:
$fourLetters = 'smit'; $query = "SELECT `company_ref` FROM `companies` WHERE `company_ref` LIKE '$fourLetters%' ORDER BY `company_ref` DESC LIMIT 1"; $last = mysqli_fetch_assoc(mysqli_query($link, $query)); $newNum = ((int) ltrim(substr($last['company_ref'],4),'0')) + 1; $newRef = $fourLetters.str_pad($newNum, 4, '0', STR_PAD_LEFT);
But I see that this causes a problem if two users try to enter company names that will result in the same ID at the same time. I will use a unique index in the column, so it will not lead to duplication in the database, but it will still cause a problem.
Can anyone think of how to get MySQL to work for me when I embed and not compute it in PHP in advance?
Please note that the actual code will be OO and will handle errors, etc. - I'm just looking for thoughts on whether there is a better way to accomplish this particular task, it is more about SQL than about anything else.
EDIT
I think the @EmmanuelN suggestion of using a MySQL trigger may be a way to handle this, but:
- I'm not good enough at MySQL, especially triggers, to get this to work, and would like a step-by-step example of creating, adding, and using a trigger.
- I'm still not sure if this will preclude the possibility of creating two identical identifiers. See
what happens if two rows are inserted at the same time that result in the trigger running simultaneously, and produce the same reference? Is there any way to lock the trigger (or a UDF) in such a way that it can only have one concurrent instance? what happens if two rows are inserted at the same time that result in the trigger running simultaneously, and produce the same reference? Is there any way to lock the trigger (or a UDF) in such a way that it can only have one concurrent instance? .
Or I would be open to any other suggested approaches to this problem.