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.
Below is the P开发者_高级运维HP 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));
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.
$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
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.
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).
Or you can use
echo nl2br($test);
精彩评论