views:

53

answers:

2
+2  Q: 

MySQL Brackets?

Latelly I've seen a lot of PHP/MySQL questions that enclose SQL values within {}, for instance:

SELECT * FROM table WHERE field LIKE '{$value}';

What's up with that? Is it even valid? Why do so many people use this weird (at least for me) syntax?

+1  A: 

Those are used to disambiguate variable names, and are absolutely required if you're using an array within a double quoted string, example:

$SQL = "Select * FROM table WHERE field LIKE '{$value[5]}'";

Wouldn't work without the braces.

Here's another great example from PHP.net

$beer = 'Heineken';
echo "$beer's taste is great"; // works; "'" is an invalid character for variable names
echo "He drank some $beers";   // won't work; 's' is a valid character for variable names but the variable is "$beer"
echo "He drank some ${beer}s"; // works
echo "He drank some {$beer}s"; // works

http://php.net/manual/en/language.types.string.php

Erik
+4  A: 

From php.net:

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

In fact, any value in the namespace can be included in a string with this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$.

danben