How can the user optimize their PHP script to efficiently handle pagination for a large number of SMS messages?

When handling pagination for a large number of SMS messages in PHP, it's important to optimize the script to efficiently fetch and display the data. One way to do this is by using SQL queries with LIMIT and OFFSET clauses to retrieve only the necessary data for each page. Additionally, caching the results can help improve performance by reducing the number of database queries.

// Assuming $page is the current page number and $limit is the number of messages per page
$offset = ($page - 1) * $limit;

// Fetch SMS messages from the database using LIMIT and OFFSET
$query = "SELECT * FROM sms_messages ORDER BY date_sent DESC LIMIT $limit OFFSET $offset";
$result = mysqli_query($connection, $query);

// Display the messages
while ($row = mysqli_fetch_assoc($result)) {
    echo $row['message'];
}

// Pagination links
$total_messages = mysqli_num_rows(mysqli_query($connection, "SELECT * FROM sms_messages"));
$total_pages = ceil($total_messages / $limit);

// Display pagination links
for ($i = 1; $i <= $total_pages; $i++) {
    echo "<a href='?page=$i'>$i</a> ";
}