AndyD273
AndyD273

Reputation: 7279

Friendly URL Database Strategies

I have a website that I want to start using friendly URLs.
So instead of:

http://server.com/company.php?id=12

I could use:

http://server.com/company/steaks_r_us

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

Answers (3)

Jakub Matczak
Jakub Matczak

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.

  1. Some websites adds ID (primary key) to the user friendly name like:

http://server.com/company/steaks_r_us_12

or in other part of URL like:

http://server.com/company/12/steaks_r_us

Then you can easily fetch the ID from the URL, but also it still looks nice.

  1. Also as wheatin suggested, you could create a field in your DB that would be this unique identifier.

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:

http://server.com/company/steaks_r_us

and

http://server.com/company/steaks_r_us2

Upvotes: 1

tom f
tom f

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

Seth
Seth

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

Related Questions