What are the best practices for structuring PHP scripts to efficiently handle user input and database interactions for displaying comments on a webpage?
When handling user input and database interactions for displaying comments on a webpage, it is important to sanitize and validate user input to prevent SQL injection and cross-site scripting attacks. Additionally, using prepared statements can help prevent SQL injection attacks when interacting with the database. It is also a good practice to limit the amount of data retrieved from the database to only what is necessary for displaying comments on the webpage.
// Sanitize and validate user input
$comment = filter_input(INPUT_POST, 'comment', FILTER_SANITIZE_STRING);
// Prepare and execute a query to insert the comment into the database
$stmt = $pdo->prepare("INSERT INTO comments (comment) VALUES (:comment)");
$stmt->bindParam(':comment', $comment);
$stmt->execute();
// Retrieve comments from the database and display them on the webpage
$stmt = $pdo->prepare("SELECT comment FROM comments");
$stmt->execute();
$comments = $stmt->fetchAll();
foreach ($comments as $comment) {
echo "<div>{$comment['comment']}</div>";
}