How can I use .htaccess & mod_rewrite to perform the following URL rewrite?
This page: http://mysite.com/page.php?id=2387281
Becomes: http://mysite.com/[criteria1]/[criteria2]
I have my database set up so the primary key is an ID number, but I want my URLs to include two fields related to that ID, but not the actual ID itself.
How can I accomplish this?
An example using what 开发者_StackOverflow社区my database structure looks like
Row 1: ID: 234 ; CRITERIA1: Food ; CRITERIA2: Steak
mysite.com/page.php?id=234 --> mysite.com/food/steak
You can't rewrite data that isn't there - you can't get a database ID that wasn't in the URL in first place.
You would have to do something like:
RewriteRule ([^/]*)/(.*) page.php?criteria1=$1&criteria2=$2
...and run a SELECT on the database at the top of the script to get the ID based on the criteria...
$result = mysql_query("SELECT id FROM table WHERE criteria1 = '".mysql_real_escape_string($_GET['criteria1'])."' AND criteria2 = '".mysql_real_escape_string($_GET['criteria2'])."'");
If I understand your right, which I think I do, then you won't use the id in the url at all. Have the modrewrite rule be something like:
RewriteRule ^([a-z0-9-]+)/([a-z0-9-]+)$ http://site.com/page.php?col1=$1&col2=$2 [L]
Then in page.php, I presume you used to have a query like:
select * from table where id=123
Just replace that query with:
"select * from table where col1='".$_GET['col1']."' and col2='".$_GET['col2']."'"
Obviously make sure the sanitize your input to prevent sql injection.
The only thing you need to ensure is that the tuple of col1 and col2 are unique and don't return more than 1 value.
So in this example, the id number is never seen in the url and actually is never used anywhere.
I don't think you can do that with mod_rewrite/.htaccess. Instead, you should use php to connect to mysql and load the data, then redirect to the appropriate page.
精彩评论