Reputation: 7279
I have a website that I want to start using friendly URLs.
So instead of:
I could use:
I know how to do this on the .htaccess side, but I don't know how to set it up on the backend with the database calls, especially if there is a chance that company name isn't unique (multiple locations for instance).
I've thought about inserting the friendly url into the database after checking for duplicates, but I'm curious if there is a better way
Upvotes: 1
Views: 162
Reputation: 15656
No matter if it's an ID or a user friendly string like company name, you need it to be a unique identifier. You won't avoid that.
There are couple of options.
or in other part of URL like:
Then you can easily fetch the ID from the URL, but also it still looks nice.
In this case you would need some additional logic at the time of creation of company row in database. That's of course because you have to handle duplicated names somehow.You could for example add a digit at the and of this value (facebook does something like that), so if a duplicate of steaks_r_us
occurs, you would insert a value steaks_r_us2
Then you would have unique URL for these companies:
and
Upvotes: 1
Reputation: 389
Wheatin has the right idea. You'd want to have a table with two columns, the URL and the id it's referring to. If you made a unique key on the URL column, then you could just have a function/method that tries to insert the clean URL with the content id; I usually do something like
###(pseudocode)
function create_unique_url($url, $id) {
try to insert the url, id combination
if success:
return url
else:
key = 1
start a loop
try to insert the url+key, id combination
if success:
return url
key++
}
Adding a number to the end is a good fail-safe way to make sure you always get a unique url returned. Sort of how Drupal or Wordpress would handle a post url with an identical name.
Upvotes: 0
Reputation: 716
You could create a unique index on the business key (in this case the company name) to prevent duplicates from being inserted in the first place.
Upvotes: 0