2

Is it an ok practice to have a URL column in my database that would store a URL such as: /this-is-a-keyword

And then use that column in my php query to get the information I need instead of using an integer column?

So basically when I went to Mysite.com/this-is-a-keyword I would return the result from that row.

steez
  • 35
  • 4

2 Answers2

5

More or less, what you are describing is called a slug and it's normally constructed by passing the most descriptive string (usually the title of the page / post) to a slugify function, like this one:

function Slug($string)
{
    return strtolower(trim(preg_replace('~[^0-9a-z]+~i', '-', html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8')), ENT_QUOTES, 'UTF-8')), '-'));
}

The problem with this, however, is that the result may not be unique, consider the following:

echo Slug('Alix Axel');          // alix-axel
echo Slug('Álix Ãxel');          // alix-axel
echo Slug('@Álix----_Ãxel!?!?'); // alix-axel

All return the same output even though the input differs. One of my favorite (and also most widespread) approaches is to do like StackOverflow does it (using the ID and slug in combination):

stackoverflow.com/questions/5845732/clean-urls-and-database

If you want to avoid this, you need to make sure the slug you are generating does not exist already in the database, if it does append an incremented number until it satisfies the unique condition.

Community
  • 1
  • 1
Alix Axel
  • 151,645
  • 95
  • 393
  • 500
  • Thanks, all the url slugs are checked to make sure they are unique. I feel like I knew the answer was yes but wanted to make sure. – steez May 01 '11 at 01:37
3

Um, sure, this is usually called a slug. And you'd just store this-is-a-keyword in the database (no leading slash) to query against.

deceze
  • 510,633
  • 85
  • 743
  • 889