views:

131

answers:

3

Forgive me, I'm a beginner. The following code returns a parse error:

$query = "INSERT INTO scenario_needgames VALUES ("$id", "Battle of the Bulge")";

the query builder in phpMyAdmin gave me this slightly modified string that works:

$query = "INSERT INTO scenario_needgames VALUES (\"$id\" , \"Battle of the Bulge\");";

but I'm confused as to why the quotes need to be escaped when they're actually part of the query syntax, and not - say - part of a title or string? The introductory book I'm learning from doesn't include those for such simple strings.

The $id value is 7 digits, 4 letters and then 3 numbers if you're curious.

Thank you.

+3  A: 

Double quotes need to be escaped within a double quoted string, alternatively you can use a single quoted string and not have to escape the double quotes, but then you cannot directly interpolate variables, you have to use concatenation instead:

$query = 'INSERT INTO scenario_needgames VALUES ("' . $id . '", "Battle of the Bulge")';

Alternatively, just replace your inner double-quotes with single-quotes:

$query = "INSERT INTO scenario_needgames VALUES ('$id', 'Battle of the Bulge')";

I would suggest using mysql_real_escape_string to correctly and safely quote strings. You might also like to have a look at using prepared statements instead with PDO or mysqli.

karim79
Please, I know, that you know it, but still could you please try not to advise people to use that awful escaping, but instead to use proper prepared statements? All this string concatenation inside a sql statement makes my eyes bleed and my brain rot. It is also not secure.
shylent
@shylent - you must have not seen my edit before you down-voted and commented.
karim79
I didn't downvote (this answer is relevant and correct, well, in a way).
shylent
`mysql_real_escape_string` is a simple change to existing code, that people can understand and enact, and used properly is perfectly secure. Whilst certainly parameterised queries should be mentioned as a good alternative, PHP doesn't currently make it easy to change to using them.
bobince
+3  A: 

They are escaping because of PHP, not MySQL. You must escape " characters in "-" string because " character can be interpreted as the end of the string.

Look at the code coloring in your answer. The first string is colored wrongly: the parts in " and " are colored like code, not string

valya
+2  A: 

It's PHP which return a parse error.

From the point of view of PHP, a string is a sequence of characters delimited by quotes. One at the beginning and one at the end.

When you want to put quotes inside the string, you need to escape them, so PHP knows the internal quotes are not the end of the string.

Unless you escape them, PHP will return a parse error because the thing you're assigning to $query is not a valid string (with a quote at each end, only)

pavium