Here is how I would do it. Maybe someone else has a better method.
Just for refrence this is the db table I set up:
Code:
CREATE TABLE `comments` (
`comment_id` smallint(6) NOT NULL auto_increment,
`comment_text` text NOT NULL,
PRIMARY KEY (`comment_id`)
);
and my html page:
Code:
<html>
<head>
<title>Post a comment</title>
</head>
<body>
<form action="comment.php" method="post">
<textarea name="comment"></textarea>
<input type="submit" value="Submit Comment" />
</form>
</body>
</html>
now the php handling file (comment.php):
Code:
<?php
//assuming a connection to the database exists
$mysql = array(); // create array of mysql escaped values
$mysql['comment'] = mysql_real_escape_string( $_POST['comment'] );
$sql = "INSERT INTO comments ( comment_text ) VALUES ( '{$mysql['comment']}' )"; //insert your comment to db
mysql_query( $sql );
?>
This is saving the line breaks and escaping your quotes. The line breaks are being saved as '\n' the newline, so you have to convert these into <br> html line breaks. Also you will want to strip out the slashes from the quotes. So to display your comments do something like (comments.php):
Code:
<?php
//assuming a connection to the database exists
$sql = "SELECT * FROM comments";
$result = mysql_query( $sql );
while( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) {
$html = array(); //create an array of html formated values.
$html['comment'] = nl2br( stripslashes( htmlentities( $row['comment_text'], ENT_QUOTES, 'UTF-8' ) ) );
echo "Comment:<br />{$html['comment']}<hr />";
}
?>
As you can see the nl2br() function is converting the \n to <br /> and the stripslashes() function is taking out the backslashes that escaped your quotes. The htmlentities converts all html markup into its proper form. The convention I used with the arrays for mysql and html came from
Chris Shiflett of
Brain Bulb which provides great PHP security information.