How should I escape characters inside this LIKE query?

后端 未结 3 750
北恋
北恋 2021-01-13 03:25

I have a field in one of my tables that contains this string:

!\"#¤%&/()=?´`?=)(/&%¤#\"!\\\'\\\'\"\'

(Only for test purposes ofcour

3条回答
  •  野的像风
    2021-01-13 04:18

    Is not clear what you are trying to obtain and what is going wrong.

    By the way, if you want to protect your query from SQL injection you should use mysql_real_escape_string
    http://dev.mysql.com/doc/refman/5.0/en/mysql-real-escape-string.html

    Assuming that you are in PHP

    $query = "SELECT * FROM mytable WHERE `column` LIKE '".mysql_real_escape_string($whatever)."'"
    

    But you have to remember that LIKE operator has his own special chars (wildchars)
    http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html#operator_like

    % Matches any number of characters, even zero characters
    _ Matches exactly one character
    

    So this chars must be escaped with backslash if you want to stop their magic

    Assuming that you are in PHP I would do

    // This removes magic on LIKE wildchars
    $whatever = preg_replace('#(%|_)#', '\\$1', $input);
    
    // This secures the query from sql injection 
    // and hads the trailing % wildchars to the search string
    $query = "SELECT * FROM mytable WHERE `column` LIKE '%".mysql_real_escape_string($whatever)."%'"
    

提交回复
热议问题