I'm looking for a way to convert a URL to something friendly using values stored in a MySQL database.

I have a control panel which allows users to enter their own friendly URL, so for example if the user entered "my-friendly-url", the URL would change from...

http://www.domain.com/page.php?pid=4&id=37

to...

http://www.domain.com/my-friendly-url

I know you can convert URLs using .htaccess, but I have no idea how to use database values in place of the querystring. As far as I know it's not possible for .htaccess to connection to a database (?)

Drupal, Joomla etc have this function, but I don't know how they do it.

Thanks for any help.