php 将textarea中的文本插入MySQL数据库而不会丢失格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5863320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inserting text from textarea into MySQL database without losing formatting
提问by Dean Perry
I am trying to add text from a textarea on my site into a MySQL database.
我正在尝试将我网站上 textarea 中的文本添加到 MySQL 数据库中。
Below is the PHP code that is adding the text to the database.
下面是将文本添加到数据库的 PHP 代码。
if (isset($_POST['text']))
{
$text = sanitizeString($_POST['text']);
$text = preg_replace('/\s\s+/', ' ', $text);
$query = "SELECT * FROM profiles WHERE user='$user'";
if (mysql_num_rows(queryMysql($query)))
{
queryMysql("UPDATE profiles SET text='$text' where user='$user'");
}
else
{
$query = "INSERT INTO profiles VALUES('$user', '$text')";
queryMysql($query);
}
}
else
{
$query = "SELECT * FROM profiles WHERE user='$user'";
$result = queryMysql($query);
if (mysql_num_rows($result))
{
$row = mysql_fetch_row($result);
$text = stripslashes($row[1]);
}
else $text = "";
}
$text = stripslashes(preg_replace('/\s\s+/', ' ', $text));
And below is the code of the form.
下面是表格的代码。
<textarea name='text' cols='40' rows='3'>$text</textarea><br />
But when the data is inputted, it shows it in the database correct but not showing it displayed properly. See the images below:
但是当输入数据时,它在数据库中显示正确但显示不正确。请参阅以下图片:
The text that is entered
输入的文本
How the text is displayed on the page
文本在页面上的显示方式
How the text is in the database
文本在数据库中的位置
This is the PHP code that displays the text on the page.
这是在页面上显示文本的 PHP 代码。
$result = queryMysql("SELECT * FROM profiles WHERE user='$user'");
if (mysql_num_rows($result))
{
$row = mysql_fetch_row($result);
echo stripslashes($row[1]) . "<br clear=left /><br />
Hope you can help!!
希望能帮到你!!
EDIT: added extra php code
编辑:添加了额外的 php 代码
回答by David says reinstate Monica
Your text, unless you're using a rich-text editor, such as Mark-down (as here on Stackoverflow), is styled by your CSS, not by the contents of the textarea
itself.
您的文本,除非您使用富文本编辑器,例如 Mark-down(如 Stackoverflow 上的此处),否则由您的 CSS 设置样式,而不是由其textarea
本身的内容设置。
If the problem is preservation of new-lines, then you could run the string through the nl2br($text)
function before storing in, or retrieving from, the database.
如果问题是换行符的保留,那么您可以在将字符串nl2br($text)
存储到数据库中或从数据库中检索之前通过该函数运行该字符串。
I'd suggest on retrieval would be better, but that's just my opinion (and I can't offer any evidence to back it up).
我建议检索会更好,但这只是我的意见(我不能提供任何证据来支持它)。
回答by arma
Or you can use
或者你可以使用
echo nl2br($test);