How does {} affect a MySQL Query in PHP?

后端 未结 3 1591
孤独总比滥情好
孤独总比滥情好 2020-12-05 15:34

What is the difference between the following 2 queries?

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

mysql_query(\"UPDATE table SET name = \'{$name}\         


        
相关标签:
3条回答
  • 2020-12-05 15:46

    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 }.

    0 讨论(0)
  • 2020-12-05 15:52

    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.

    0 讨论(0)
  • 2020-12-05 16:08

    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.

    0 讨论(0)
提交回复
热议问题