将文本从textarea插入MySQL数据库而不丢失格式 [英] Inserting text from textarea into MySQL database without losing formatting
问题描述
我正在尝试将站点上文本区域中的文本添加到MySQL数据库中.
I am trying to add text from a textarea on my site into a MySQL database.
下面是将文本添加到数据库的PHP代码.
Below is the PHP code that is adding the text to the database.
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));
下面是表单的代码.
<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:
输入的文本
文本在页面上的显示方式
文本在数据库中的显示方式
这是在页面上显示文本的PHP代码.
This is the PHP code that displays the text on the page.
$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 />
希望您能提供帮助!
添加了额外的php代码
added extra php code
推荐答案
您的文本(除非您使用的是RTF编辑器,例如Mark-down(如Stackoverflow上所示))是由CSS设置样式的,而不是通过textarea
本身的内容.
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.
如果问题是保留换行符,则可以通过 nl2br($text)
在存储到数据库中或从数据库中检索之前起作用.
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.
我建议检索会更好,但这只是我的意见(我无法提供任何证据来支持它).
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).
这篇关于将文本从textarea插入MySQL数据库而不丢失格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!