Genadinik
Genadinik

Reputation: 18629

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.

Upvotes: 4

Views: 2872

Answers (6)

kushalbhaktajoshi
kushalbhaktajoshi

Reputation: 4678

How about this one just in case you don't wanna break the pattern of your query.

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

When you apply single quote don't include the php variable inside it as this single quote treats everything inside it as value not variable.

Upvotes: 0

Morten Kristensen
Morten Kristensen

Reputation: 7613

You use a single quote as the start of your string and again single quotes "inside" it. You could change it to the following:

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

Upvotes: 1

Ghpst
Ghpst

Reputation: 309

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

Should solve your problem.

Upvotes: 1

alex
alex

Reputation: 490143

You are using single quotes inside a single quote delimited string. Try using double quotes to quote your string.

Upvotes: 1

Byron Whitlock
Byron Whitlock

Reputation: 53851

Surround the whole thing in double quotes.

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

Upvotes: 4

RichardTheKiwi
RichardTheKiwi

Reputation: 107696

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

Upvotes: 5

Related Questions