添加斜杠,mysql_real_escape总是添加两个斜杠?
我在将 JSON 插入数据库时遇到问题,我的目的是获取变量,对它们进行 json_encode,删除斜杠(从 magic_quotes 中),然后添加斜杠以转义 {"key":"value"} 中的引号
不幸的是,编码字符串上的 strip_slashes 没有做任何事情,并且输出了这个
{"content":"<p>This string has it\'s downsides</p>","date":1271352514}
我然后尝试了addslashes和mysql_real_escape_string,这两个输出
"{\\"content\\":\\"<p>This string has it\\\'s downsides</p>\\",\\"date\\":1271352514}"
我无法弄清楚为什么它添加了两个斜杠?我为此抓狂,每次我尝试去掉斜杠时,都会留下一个,而添加斜杠则会增加两个。任何帮助将不胜感激!
I'm having an issue with inserting JSON into a database, my intention is to take the variables, json_encode them, remove slashes (from magic_quotes), and then addslashes back in to escape the quotes in {"key":"value"}
Unfortunately, strip_slashes on the encoded string isn't doing anything, and outputs this
{"content":"<p>This string has it\'s downsides</p>","date":1271352514}
I have then tried addslashes, and mysql_real_escape_string, both output
"{\\"content\\":\\"<p>This string has it\\\'s downsides</p>\\",\\"date\\":1271352514}"
I can't work out why it's adding in two slashes? And I'm tearing my hair out over this, everytime I try to stripslashes it leaves one in, and adding slashes adds two. Any help would be hugely appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,你真的应该考虑关闭
magic_quotes
...引用手册:话虽如此,使用
json_encode()
构建 JSON 数组(而不是构建你自己的),并在查询时通过一次调用mysql_real_escape_string()
来结束因此:此外,PHP 组建议您使用
mysqli
而不是mysql
。其面向对象的 API 和对参数化查询的支持极大地提高了开发速度、代码维护和安全性。以下是使用
mysqli
编写的上述代码:First, you should really consider turning
magic_quotes
off... To quote the manual:That being said, use
json_encode()
to build your JSON array (instead of building your own), and finish off with a single call tomysql_real_escape_string()
while querying as such:Also, the PHP group recommends you use
mysqli
instead ofmysql
. Its Object Oriented API and support for parametrized queries greatly improve both development speed, code maintenance and security.Here is the above code written using
mysqli
:如果你已经有一个像这样的 JSON 字符串(顺便说一句:在 JSON 中
/
也需要转义):那么你只需要应用
mysql_real_escape_string
对它进行转义,以便可以将其插入到 MySQL 字符串声明中:如果您启用了 Magic Quotes,您应该在此步骤之前禁用或删除它们,以便您的
$json
字符串实际上只是有效的 JSON。If you already have a JSON string like this (by the way: In JSON the
/
needs to be escaped too):Then you just need to apply
mysql_real_escape_string
on it to escape it so that it can be used to insert it into a MySQL string declaration:And if you have Magic Quotes enabled, you should disable or remove them before that step so that your
$json
string is really just valid JSON.