Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rewrite urls for product name

i want to rewrite a rule for my products.

i want to use the id and name in the url separated by a dash like this:

123-name means product id = 123 and name = name

so in my php i can get the $_GET[id] and then query my database using this id like this:

$sql = "SELECT * from Products Where productid = " . $_GET[id];

here's what i have:

RewriteEngine On
RewriteRule ^products/([0-9+])\-([a-z]+)/?$ products.php?id=$2 [NC,L] 

but when i put this as url, i get a 404

why?

like image 391
natalia Avatar asked Dec 25 '11 16:12

natalia


1 Answers

First: you have a syntax error. [0-9+] is a character class that can match (i) digits in the range 0 through 9, or (ii) a + sign. To use the + as a quantifier (as intended), move the + after the ], like so: ([0-9]+).

Second: You are using $2 in your item which is the product name. If you want to use the ID, you have to use $1.

Here's what you need to use:

RewriteEngine On
RewriteRule ^products/([0-9]+)\-([a-z0-9_\-]+)/?$ products.php?product_id=$1 [NC,L,QSA]

I added in the product numbers, dash and underscore in case you need it someday.

Third: You should be aware of sql injections, your script is not safe. You can fix this by using mysql_real_escape_string.

like image 168
Book Of Zeus Avatar answered Oct 04 '22 09:10

Book Of Zeus