Search code examples
phpmysqlsqlquotes

PHP quotes with a like query


I have gotten myself into a tangled mess with quotes.

I am trying to do a like query that looks something like this

$myQuery = 'SELECT col1 , col2 from my_table WHERE col_value LIKE '%$my_string_variable%';

But this query would obviously give an error. What is the right syntax for this? I tried messing with double-quotes, but that didn't work either.


Solution

  • Combine double and single quotes.

    $myQuery = "SELECT col1 , col2
                FROM my_table
                WHERE col_value LIKE '%$my_string_variable%'";
    

    Although I prefer to protect my code against SQL Injection..

    $myQuery = "SELECT col1 , col2
                FROM my_table
                WHERE col_value LIKE '%" . mysql_real_escape_string($my_string_variable) . "%'";