How to store escaped characters in MySQL and display them in php?

亡梦爱人 提交于 2020-01-11 12:52:07

问题


For example I want to store the String "That's all". MySQL automatically escapes the ' character. How do I echo that String from the database using php but remove the \ in front of escaped characters like \' ? I would also like to preserve other formatting like new lines and blank spaces.


回答1:


Have you tried stripslashes(), regarding the linebreaks just use the nl2br() function.

Example:

$yourString = "That\'s all\n folks";
$yourString = stripslashes(nl2br($yourString));
echo $yourString;

Note: \\ double slashes will turn to \ single slashes


You should probably setup your own function, something like:

$yourString = "That\'s all\n folks";

function escapeString($string) {
    return stripslashes(nl2br($string));
}

echo escapeString($yourString);

There are also several good examples in the nl2br() docs


Edit 2

The reason your are seeing these is because mysql is escaping line breaks, etc. I am guessing you are using mysql_* functions. You should probably look into mysqli or PDO.

Here is an example:

$yourString = "That's all
 folks";
echo mysql_escape_string($yourString);

Outputs:

That\'s all\r\n folks




回答2:


If you use prepared statements, those characters will not be escaped on insert.

Use stripslashes() to remove slashes if you cannot avoid adding slashes on input.




回答3:


At first, magic_quotes_gpc escapes the character like ' or ". You can also disable this in your php.ini. But then you should escape the things yourself that no query can get "infected". Lookup mysql injection for more information.

When the escaped string is been written in your database. The string doesn't contain theses escape charakters and when you output them again. You should see the result as you want it.

Me for myself prefer the method by storing everything without escapes and escape or display things when I output them. You could also easily use an str_replace("\n", "", $text) to prevent newslines are displayed.

Greetings MRu



来源:https://stackoverflow.com/questions/15510082/how-to-store-escaped-characters-in-mysql-and-display-them-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!