Search code examples
phpmysqlvariablesevaluate

mysql update query with php variable and dots around it


So, I'm learning PHP and I have a question about the part underlined in my screenshot:

http://s18.postimg.org/8el9lkpuh/image.png

I read these related questions and they were generally helpful (and I realize there are security concerns not handled here) but didn't help my understand my specific question:

concatenate mysql select query with php variable?

MySQL query with PHP variables Issues

My question is, why do we need these dots around the variable? Are these concatenation dots? I don't think we are concatenating anything, we're just evaluating a variable, no? And why does it need quotation marks around it? Why can't it simply be "UPDATE table WHERE name=$name" and let $name evaluate to whatever it is..? In fact, when I try to do that it just doesn't evaluate, but why? A few lines below, echo "<p>Name: $row[1]</p>";, $row for example evaluates just fine...

EDIT:

$q='UPDATE towels SET name="$name" WHERE id=1'; output: $name my variable is inside doublequotes, so it should get evaluated, but doesn't?

$q='UPDATE towels SET name="$name" WHERE id=1'; output: $name variable inside doublequotes, should get evaluated, but doesn't?

$q='UPDATE towels SET name="'.$name.'" WHERE id=1'; output: CORRECT! variable inside singlequotes, shouldn't get evaluated, but does?

$q="UPDATE towels SET name='$name' WHERE id=1"; output: CORRECT! variable inside singlequotes, shouldn't get evaluated, but does?

So clearly I'm missing something because it all seems opposite than it should be to me.


Solution

  • The . is indeed a concatenation operator.

    When the statement you underlined is processed, the bits in between '' are processed literally, and those outside the '' are evaluated.

    Because you want $name to be converted to it's value (rather than just having the text $name within your SQL), you must put it outside the '', and the . just tells the compiler to package the whole statement into one long concatenated string.

    Take a look at this ... http://phphowto.blogspot.co.uk/2006/12/concatenate-strings.html ... for more information about concatenation.

    echo allows for a different way of using variable values (they are evaluated within the echo argument ... see here for details ... http://php.net/Echo


    In answer to your comment, you need to imagine that statement as three distinct blocks UPDATE Towels SET Name=" is the first part of the string, $name is the second part, and " WHERE Id=1 is the third part.

    They all come together to say UPDATE Towels SET Name="John" WHERE Id=1.

    You need the "" around the John value because that is the format expect in the SQL statement - and since you want those "" taken literally, they belong inside the ''.

    It's confusing to start with, but you will get the hang of it!