Reputation: 35
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.
Upvotes: 2
Views: 533
Reputation: 154543
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.
Upvotes: 5