apache .htaccess rule with dynamic pages (php) performance apache .htaccess rule with dynamic pages (php) performance mysql mysql

apache .htaccess rule with dynamic pages (php) performance


Unfortunately using a name and convert it to a unique id might take longer to execute than creating an index on the name itself.

Here's what I recommend based on the urls you have:

Add a index to the name of the page

ALTER TABLE `mytable` ADD key indexname (columnname);

example:

ALTER TABLE `page` ADD key pagename (name);

Now, because the structure is different /candy vs /candy/chocolate, I assume you have some sort of structure like a main page with the list (/candy) and specific list (/candychocolate) so in this case you can use this:

RewriteRule ^([a-z]+)/?$ index.php?category=$1&page=list [NC,L]RewriteRule ^([a-z]+)/([a-z]+)/?$ index.php?category=$1&page=$2 [NC,L]

Then you can simply query the category and the page using the indexed field. This will fast (of course not as fast as an INT but still fast).

For the first query you can do:

$name = addslahes($name);SELECT fields FROM category WHERE category = '$name';

and when you get a page you can use:

$categoryname = addslahes($categoryname);$pagename = addslahes($pagename);SELECT fields FROM page LEFT JOIN category ON (page.categoryid = category.id) WHERE page = '$pagename' AND category = '$categoryname';

this way, by using both category and page, you will avoid page not found (404).


Just make sure your database has an index for the name row. That will make the lookup just as fast as using a integer primary key.

Use something like CREATE INDEX name ON mytable I think, but doing it via phpmyadmin is a lot easier.

Also protect the script from sql injection by using addslashes

$sql = "SELECT myfields FROM mytable WHERE name = '" . addslashes($_GET['category']) . "'";


The identifier used in URL should be unique and have a database index. If both the ID and category name are unique and indexed, then it's performance-wise the same, but I would recommend using the name as it is more search engine-friendly and descriptive than an internal ID, which becames especially important when a URL is displayed somewhere without much additional context (eg., example.org/1 vs. example.org/shoes printed in a newspaper). If not, then use ID and change the rewrite rule to:

RewriteRule ^(\d+)/([a-z]+)/?$ index.php?category=$1&page=$2 [NC,L]

(Btw, \d+ should also be used for page if it is numeric.)