xRobot
xRobot

Reputation: 26567

Is there a way to rewrite this URL?

I need to rewrite URLs from:

www.example.com/John.Connor/my-first-post/42

to:

www.example.com/post.php?postid=42&userid=19

Tables:

USER:
id, name, surname, email, password

POST:
id, title, post, userid

Is there a way to do that ?

Upvotes: 1

Views: 81

Answers (1)

anubhava
anubhava

Reputation: 785156

Well mod_rewrite cannot query your database hence it cannot be completely done via .htaccess itself. What you can do is to have this rule in .htaccess:

Enable mod_rewrite and .htaccess through httpd.conf and then put this code in your .htaccess under DOCUMENT_ROOT directory:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteRule ^[^/]+/[^/]+/([0-9]+)/?$ post.php?postid=42 [L,QSA]

Then inside your post.php script have code like this:

$postid = mysql_real_escape_string($_GET['postid']); 
$userid = mysql_real_escape_string($_GET['userid']);

if (empty($userid)) {
   $userid = mysql_result(mysql_query("SELECT userid FROM POST WHERE id=$posid"), 
              0, "userid");
   // now redirect by appending &userid=49 in the current URL
   header("Location: " . $_SERVER["REQUEST_URI"] . "&userid=" . $userid);
   exit;
}

Upvotes: 1

Related Questions