Liam
Liam

Reputation: 9855

URL Rewrite query database?

I'm trying to understand how URL rewriting works. I have the following link.

mysite.com/profile.php?id=23

I want to rewrite the above url with the users first and last name.

mysite.com/directory/liam-gallagher

From what I've read however you specify the rule for what the url should be output as, but how do I query my table to get each user name?

Sorry if this is hard to understand, I've confused myself!

Upvotes: 0

Views: 1988

Answers (3)

Peon
Peon

Reputation: 8020

You are looking at this from the wrong direction. You can't do that kind of automatic url rewrite. The best is to create an all over url rewrite:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>

and create a specific name for a user in the db that will be used as an url.

+---------+----------+------+-----------+----------------+
| user_id | username | name | surname   | url            |
+---------+----------+------+-----------+----------------+
|      23 | liam     | Liam | Gallagher | liam-gallagher |
+---------+----------+------+-----------+----------------+

Now when someone accesses your http://mysite.com/directory/liam-gallagher, you can read the last entry and find the user_id in you database and make your script do the rest.

The other way is as Pekka suggested. Create an url like http://mysite.com/directory/23/liam-gallagher and read the id from the link. But I personally don't like that kind of urls. They are just fast/lazy workarounds in my opinion.

Upvotes: 6

Endy
Endy

Reputation: 696

One approach I've used works as follows.

Make a rewrite rule, e.g.

mysite.com/directory/(.*)

That redirects to:

mysite.com/profile.php?user=%1

Having %1 as the parameter captured from the rule.

Then grab the user from the query parameter on the profile page and fetch the ID for that user from the db.

http://httpd.apache.org/docs/current/mod/mod_rewrite.html

Upvotes: 0

Nirav Ranpara
Nirav Ranpara

Reputation: 13785

Something like (just a draft, adapt to your own needs...):

RewriteEngine On
RewriteRule ^([a-zA-Z]+)/([a-zA-Z]+)/([0-9]+)/([-0-9a-zA-Z]+)/?$ /$1/$2.php?id=$3 [L]

Upvotes: 0

Related Questions