像$ variable这样的LIKE运算子 [英] LIKE operator with $variable

查看:75
本文介绍了像$ variable这样的LIKE运算子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在这里的第一个问题,我希望它足够简单,可以快速获得答案!

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运算子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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