Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

php - LIKE operator with $variable

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' ;

If I echo the $variable, it prints the current page's url( which is a javascript on my page)

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!

I tried :

    $query = 'SELECT * FROM `tablename` WHERE `columnname` LIKE '"echo $variable" ' ;

But again, I'm probably missing or using a misplaced ' " ; etc.

Please tell me what I'm doing wrong!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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}%'";

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.

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.

edit 17 Jan 2015: Just got an upvote, so with that in mind, please don't use the mysql_* functions anymore.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...