How can the PHP script be optimized to improve performance when fetching and displaying comments for a tutorial from a database?
The PHP script can be optimized by using SQL queries to fetch only the necessary data for displaying comments, avoiding unnecessary data retrieval. Additionally, utilizing prepared statements can help prevent SQL injection attacks and improve query performance. Caching the fetched comments can also reduce database queries and improve overall performance.
// Fetch and display comments for a tutorial from a database
// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=your_database", "username", "password");
// Fetch comments using prepared statement
$stmt = $pdo->prepare("SELECT comment_text, user_name FROM comments WHERE tutorial_id = :tutorial_id");
$stmt->bindParam(':tutorial_id', $tutorial_id, PDO::PARAM_INT);
$stmt->execute();
$comments = $stmt->fetchAll();
// Display comments
foreach ($comments as $comment) {
echo "<div><strong>{$comment['user_name']}</strong>: {$comment['comment_text']}</div>";
}