What are the best practices for storing and retrieving user comments in a PHP application?
When storing and retrieving user comments in a PHP application, it is important to sanitize user input to prevent SQL injection attacks and cross-site scripting vulnerabilities. It is also recommended to store comments in a database table with appropriate indexing for efficient retrieval.
// Sanitize user input before storing in the database
$comment = htmlspecialchars($_POST['comment']);
$comment = mysqli_real_escape_string($conn, $comment);
// Store the comment in the database
$sql = "INSERT INTO comments (comment) VALUES ('$comment')";
mysqli_query($conn, $sql);
// Retrieve comments from the database
$sql = "SELECT * FROM comments";
$result = mysqli_query($conn, $sql);
// Display comments
while ($row = mysqli_fetch_assoc($result)) {
echo $row['comment'] . "<br>";
}