MySQL PHP Escape String'\' - 为什么没有使用反斜杠保存在数据库中? [英] MySQL PHP Escape String '\' - Why is it not saved in the database with the backslash?

查看:540
本文介绍了MySQL PHP Escape String'\' - 为什么没有使用反斜杠保存在数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对转义字符串和如何存储在数据库中感到困惑

Confused about escape string and how it is stored in the database

在我的MySQL调用中,我转义了一个带有反斜杠的字符串:

In my MySQL call, I escaping a string with a backslash:

UPDATE `TABLE` SET `PERSONAL_BELONGINGS` = 'Tom\'s things'

但是当我看到phpadmin时,值被保存如下:

But when I look in the phpadmin - the value was saved like this:

|Tom's things|

为什么反斜杠没有保存到数据库中?
当我将这个值读入javascript,然后尝试传递它时,会导致问题 - 我的JavaScript字符串将会终止。这就是为什么我逃避了角色开始。

Why is the backslash not saved into the database? This causes problems when I read this value into javascript and then try passing it around - my javascript strings will terminate. This is why I escaped the character to begin with.

为什么MySQL在保存到数据库之前删除'\'反斜杠?

如果不使用'\'保存在数据库中 - 那么最好的方法是将其传递回javascript作为字符串?要将它作为一个字符串传递给JavaScript时再次逃脱?

推荐答案

让我开始说你应该真的数据库中没有真正存储任何特殊转义格式的数据,如果您需要以其他格式解压缩或稍后搜索数据,您将后悔。您现在保存的格式现在看起来不错,并且在将数据传递给实际的Javascript时,在Javascript中添加反斜杠更好。

Let me begin by saying that you should really not really store data in any particular escaped format in the database, you'll regret it later if you need to extract it in another format or search the data for some reason later. The format you're saving now looks good, and adding backslashes for Javascript is better done in code when passing the data to the actual Javascript.

现在这就是为什么它当前

Now this is why it currently behaves like it does;

在字符串Tom的东西中, \'字符转义序列,并且真的只用于让MySQL了解如何解析SQL字符串,它从未保存到数据库。

In the string 'Tom\'s things', \' is a character escape sequence and is really only used to let MySQL understand how to parse the SQL string, it's never saved as is to the database.

您逃脱的原因您开始显示的SQL语句中的字符'是否否则MySQL无法知道字符串不会以'Tom

The reason you escape the character ' in the SQL statement you're showing to begin with is that otherwise MySQL has no way of knowing that the string does not end at the single quote after 'Tom.

如果您使用MySQLi或PDO准备的语句,而不是自己构建SQL语句,MySQL将允许您保存值完全没有变化,无需永远e踩任何东西这绝对是首选,因为不支持准备语句的MySQL API反而被弃用。

If you use MySQLi or PDO prepared statements instead of building your SQL statements yourself, MySQL will let you save values entirely unchanged without having to ever escape anything. This is definitely the preferred option, since the MySQL API that does not support prepared statements is deprecated anyway.

这篇关于MySQL PHP Escape String'\' - 为什么没有使用反斜杠保存在数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆