How to use PHP string in mySQL LIKE query?

后端 未结 2 1905
感情败类
感情败类 2020-12-10 04:27

I am trying to find the number of rows that match a specific pattern. In this example, all that START with \"123\":

This is working:

$query = mysql_q         


        
相关标签:
2条回答
  • 2020-12-10 04:55

    DO it like

    $query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");
    

    Do not forget the % at the end

    0 讨论(0)
  • 2020-12-10 05:15

    You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like

    $query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");
    

    You can confirm this by printing out the string to see that it turns out identical to the first case.

    Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string, which would make it look perhaps like this:

    $sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
                   mysql_real_escape_string($prefix));
    $query = mysql_query($sql);
    

    Note that inside the first argument of sprintf the percent sign needs to be doubled to end up appearing once in the result.

    0 讨论(0)
提交回复
热议问题