重写产品名称的网址 [英] rewrite urls for product name

查看:112
本文介绍了重写产品名称的网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的产品重写规则.

我想在网址中使用ID和名称,并用破折号分隔,如下所示:

123名称表示产品ID = 123,名称=名称

因此在我的php中,我可以获取$ _GET [id],然后使用该ID查询我的数据库,如下所示:

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

这是我所拥有的:

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

但是当我将其作为url时,我得到了404

为什么?

解决方案

首先:您遇到语法错误. [0-9+]是一个字符类,可以匹配(i)在09范围内的数字,或(ii)一个+符号.要将+用作量词(按预期使用),请将+移到]之后,如下所示:([0-9]+).

第二:您正在产品中使用$2作为产品名称.如果要使用ID,则必须使用$1.

这是您需要使用的:

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

我添加了产品编号,破折号和下划线,以备将来有需要时使用.

第三: 您应该注意 sql注入,您的脚本不安全.您可以使用 mysql_real_escape_string 来解决此问题. >

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.

这篇关于重写产品名称的网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆