这是我在这里的第一个问题,我希望它足够简单,可以快速获得答案!
This is my first question here and I hope it is simple enough to get a quick answer!
基本上,我有以下代码:
Basically, I have the following code:
$variable = curPageURL(); $query = 'SELECT * FROM `tablename` WHERE `columnname` LIKE '$variable' ;如果我回显$ variable,它将打印当前页面的url(这是我页面上的javascript)
If I echo the $variable, it prints the current page's url( which is a javascript on my page)
最终,我想要的是能够进行搜索,搜索条件是当前页面的url,前后带有通配符.我不确定这是否可能,或者我只是语法错误,因为我没有错误,只是没有结果!
Ultimately, what I want, is to be able to make a search for which the search-term is the current page's url, with wildcards before and after. I am not sure if this is possible at all, or if I simply have a syntax error, because I get no errors, simply no result!
我尝试过:
$query = 'SELECT * FROM `tablename` WHERE `columnname` LIKE '"echo $variable" ' ;但是再次,我可能丢失了或使用了错误的';等.
But again, I'm probably missing or using a misplaced ' " ; etc.
请告诉我我做错了!
推荐答案
最终,我想要的是能够进行搜索,搜索条件是当前页面的url,前后带有通配符.
Ultimately, what I want, is to be able to make a search for which the search-term is the current page's url, with wildcards before and after.
SQL通配符是一个百分号.因此:
The SQL wildcard character is a percent sign. Therefore:
$variable = curPageURL(); $variable = mysql_real_escape_string($variable); $query = "SELECT * FROM `tablename` WHERE `columnname` LIKE '%{$variable}%'";注意:我添加了一些额外的代码. mysql_real_escape_string()将保护您免受用户有意或无意间放置会破坏SQL语句的字符的侵害.您最好使用参数化查询,但这是比此简单修复更复杂的话题.
Note: I've added in an extra bit of code. mysql_real_escape_string() will protect you from users deliberately or accidentally putting characters that will break your SQL statement. You're better off using parameterised queries, but that's a more involved topic than this simple fix.
还请注意:我也修复了您的字符串引用.仅当字符串中的变量用双引号引起来并且您在$query的末尾缺少引号时,才可以直接使用该变量.
Also note: I've fixed your string quoting, too. You can only use a variable in a string directly if that string is double quoted, and you were missing a quote at the end of $query.
编辑2015年1月17日::刚刚通过投票,因此,请请不要再使用mysql_*功能.
edit 17 Jan 2015: Just got an upvote, so with that in mind, please don't use the mysql_* functions anymore.
更多推荐
像$ variable这样的LIKE运算子
发布评论