简体   繁体   English

php mysql查询有关“”的语法问题

[英]php mysql query syntax question regarding “”'s

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: phpMyAdmin中的查询生成器为我提供了这个经过稍微修改的字符串,可以正常工作:

$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. $ id的值是7位数字,4个字母,如果您感到好奇的话,然后是3个数字。

Thank you. 谢谢。

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. 我建议使用mysql_real_escape_string正确并安全地引用字符串。 You might also like to have a look at using prepared statements instead with PDO or mysqli . 您可能还想看看将准备好的语句与PDOmysqli一起使用

They are escaping because of PHP, not MySQL. 他们逃避是因为PHP,而不是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 第一个字符串的颜色错误:“和”中的部分的颜色类似于代码,而不是字符串

It's PHP which return a parse error. 这是PHP,它返回解析错误。

From the point of view of PHP, a string is a sequence of characters delimited by quotes. 从PHP的角度来看,字符串是由引号分隔的字符序列。 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. 当您想将引号放在字符串中时,需要对其进行转义,因此PHP知道内部引号不是字符串的结尾。

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) 除非您对它们进行转义,否则PHP将返回解析错误,因为您要分配给$query内容不是有效的字符串(仅在两端加上引号)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM