Jump to content
Larry Ullman's Book Forums

Recommended Posts

Hello forum members,

 

I realize that the book PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide (4th Edition) does not cover URL rewriting, but I hope I can still get some advice on this technique. :)

 

I can have an URL in my HTML such as:

http://www.mystore.com/France/Paris

which gets redirected to:

http://www.mystore.com/index.php?country=France&city=Paris

But what must I do about a pagination link such as:

// Make all the numbered pages:	
for ($i = 1; $i <= $pages; $i++) {
if ($i != $current_page) {
echo '<a href="index.php?s=' . (($display * ($i - 1))) . '&p=' . $pages . '';

if(isset($city)) {
echo'&city='.$city.'';
}
echo'&sort='.$sort.'">' . $i . '</a> ';
}
else {
echo $i . ' ';
}
} // End of FOR loop.

Surely I can't put the above code into my .htaccess file?

 

Thank you in advance for any help.





			
		
Link to comment
Share on other sites

You can just tack a number onto the end for pagination. For example:

http://www.mystore.com/France/Paris/2/

 

And just like regular pagination, no number would be the same thing as "1".

And yes, you can move all this logic to your .htaccess file with mod_rewrite, but you can't do looping, etc., so you instead need to use a regex.

 

For example:

RewriteRule (\w+)/(\w+)/(\d+)/? index.php?country=$1&city=$2&page=$3

Now, please keep the following in mind:

  1. The above line of code is not the only thing required for mod_rewrite, but it's the main part. Please see Larry's advanced PHP book or online resources for mod_rewrite for details.
  2. You probably should add to the above regex, as it's not robust enough to handle the optional page parameter, etc.

 

That all make sense?

Link to comment
Share on other sites

  • 3 months later...

Hi HartleySan,

 

how are you doing?
 

I have a question about URL rewriting. Hope you can give me some advice.

 

The names in my URLs are separated with dashes, for example, /world-football-association/. I then use str_replace() to replace the dashes with spaces before I use the names in a database query. But what about those names in the database that do have dashes between them? Must I first loop all of the names into an array and then not run the str_replace() function on those that do have dashes as a separator? Or is there some other technique that I should use?

 

 

Thank you for your time!

Link to comment
Share on other sites

You should not use strings that have to be modified to query the DB.

Going that route, there are too many exceptions and too many what ifs that you have to account for.

 

Instead, add a number to the URL that serves as a primary key in the DB, and then you can make the rest of the URL whatever you want, and you don't have to worry about the problems you are currently facing.

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...