简体   繁体   English

将 textarea 中的文本插入 MySQL 数据库而不丢失格式

[英]Inserting text from textarea into MySQL database without losing formatting

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输入的文本

the text that is entered

How the text is displayed on the page文本在页面上的显示方式

this is how the text is displayed

How the text is in the database文本在数据库中的情况

this is the text 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 代码

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) function 运行字符串。

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).我建议检索会更好,但这只是我的意见(我不能提供任何证据来支持它)。

Or you can use或者你可以使用

echo nl2br($test);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM