Akos
Akos

Reputation: 2007

What is the difference between $variable and %$variable%?

I have this piece of code here:

$query = mysql_query("SELECT * FROM example WHERE text LIKE '%$value%'");

Would it make a difference if I would use:

$query = mysql_query("SELECT * FROM example WHERE text LIKE '$value'");

If yes, what would it be? What would be the difference?

Upvotes: 3

Views: 482

Answers (4)

Sylvain Cleymans
Sylvain Cleymans

Reputation: 1907

The difference is that '%$value%' will seach for matches containing $value (for exemple if $value = 'foo' it could return 'foobar' or 'barfoobar'), '$value' only matches the exact value of $value.

Upvotes: 2

Adithya Surampudi
Adithya Surampudi

Reputation: 4454

Yes this has nothing to do with php, its a sql thing, % means like a wildcard there could be 0 or more characters instead of it.

%abc% matches abc, aabca, aabc, abcd
%abc matches dabc, abc but not abcd or tabcd
abc% matches abcd, abc but not dabc, tabcd

Upvotes: 9

JamesHalsall
JamesHalsall

Reputation: 13485

In PHP there is no difference (although you might want to take a look at using PDO for your database queries), the '%' symbols affect the query executed in MySQL.

% acts as a wildcard so the first result will return anything that contains the term 'value' in its text attribute, whereas the second will return only records that match exactly the term 'value'

Upvotes: 1

Prisoner
Prisoner

Reputation: 27618

Its not a difference in PHP, its a wildcard in SQL. You can read more about it here. Essentially, %

Matches any number of characters, even zero characters

Upvotes: 12

Related Questions