繁体   English   中英

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

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

我正在尝试将我网站上的 textarea 中的文本添加到 MySQL 数据库中。

下面是将文本添加到数据库的 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));

下面是表格的代码。

<textarea name='text' cols='40' rows='3'>$text</textarea><br /> 

但是当输入数据时,它在数据库中显示正确,但显示不正确。 请参阅下面的图片:

输入的文本

the text that is entered

文本在页面上的显示方式

this is how the text is displayed

文本在数据库中的情况

this is the text in the database

这是在页面上显示文本的 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 />

希望你能帮忙!!

编辑:添加了额外的 php 代码

除非您使用的是富文本编辑器,例如 Mark-down(如 Stackoverflow 上的此处),否则您的文本由您的 CSS 设置样式,而不是由textarea本身的内容设置样式。

如果问题是保留换行符,那么您可以在存储到数据库或从数据库中检索之前通过nl2br($text) function 运行字符串。

我建议检索会更好,但这只是我的意见(我不能提供任何证据来支持它)。

或者你可以使用

echo nl2br($test);

暂无
暂无

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

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