I have a database (SQL) with a lot of names and I'd like to create alphabetical buttons so it's easy to navigate. I've found lots of examples on how to create an alphabet in PHP. However, I want to build an alphabet with only valid letters depending on the names on the database.
For example:
The database lists: Anderson, Beresford, Donovan, Emerson, Graham....
I'd like the alphabet to appear as: A B D E G ...
(Notice that C and F do not appear).
The only way I can think of is to
-select every name in the database, -order by last name -loop one by one, find what the first character is, save it to an array, -loop to the second one, get the first character, see if it already exists in the array and if it does ignore it -do this on and on until I'm left with an array of only unrepeated letters.
Is this the only way? Or am I missing a simpler solution?
Thanks in advance.
SELECT DISTINCT SUBSTRING(lastname,1,1) 'initial'
FROM people
ORDER BY initial ASC
Bear in mind that this is a string operation on every row in the database, followed by an unindexed sort operation. It will not perform well at all once the table becomes large.
SELECT LEFT(name, 1) AS firstletter
FROM database
GROUP BY firstletter
ORDER BY last_name
Works for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With