LIKE operator with $variable

后端 未结 6 1990
有刺的猬
有刺的猬 2020-12-18 13:24

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();
         


        
6条回答
  •  自闭症患者
    2020-12-18 13:51

    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.

提交回复
热议问题