16

What is the difference between the following 2 queries?

mysql_query("UPDATE table SET name = '$name'");

mysql_query("UPDATE table SET name = '{$name}'");
James Simpson
  • 13,488
  • 26
  • 83
  • 108
  • 1
    I've yet to encounter SQL syntax that uses curly brackets. – OMG Ponies Mar 20 '11 at 18:19
  • 4
    The sample code may be vulnerable to [SQL injection](http://unixwiz.net/techtips/sql-injection.html), which is a very serious [security risk](http://bobby-tables.com/). To fix this hole, switch from the outdated mysql driver to [PDO](http://php.net/PDO) and use [prepared statements](http://www.php.net/PDO.prepared-statements). If you need a PDO tutorial, try ["Writing MySQL Scripts with PHP and PDO"](http://www.kitebird.com/articles/php-pdo.html). The site you save may just be your own. – outis Mar 20 '11 at 18:23
  • The curly braces are a PHP thing not a MySQL thing, FYI – Joe Phillips Mar 20 '11 at 18:26

3 Answers3

23

ON the SQL side, there is absolutely no difference : the two queries are exactly the same.
(you can check that by echo-ing them)

{$variable} is a more complete syntax of $variable, that allows one to use :

  • "this is some {$variable}s"
  • "{$object->data}"
  • "{$array['data']}"
  • "{$array['data']->obj->plop['test']}"


For more informations, you should read the Variable parsing / Complex (curly) syntax section of the manual (quoting a few bits) :

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

Any scalar variable, array element or object property with a string representation can be included via this syntax.
Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }.

Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
8

The curly braces "escape" the PHP variable and are not passed to MySQL. With a simple variable like $name it doesn't make a difference but with something like $user['name'] it does. So there is nothing different between the two queries you have posted in your question.

Treffynnon
  • 21,365
  • 6
  • 65
  • 98
2

This query can be used if you want to pass a single variable:

mysql_query("UPDATE table SET name = '$name'");

This can be used if you are passing a value from an array's particular index.

mysql_query("UPDATE table SET name = '{$1}'",$name);

By the way your both queries were also correct in their means.

Sujit Agarwal
  • 12,348
  • 11
  • 48
  • 79
  • Note you can [format lines as code](http://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks) by indenting them four spaces. The "{}" button in the editor toolbar does this for you. Edit your answer and try it out. Click the orange question mark in the editor toolbar for more information and tips on formatting. – outis Mar 20 '11 at 18:47