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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With