How can the PHP code be optimized to improve the performance of the pagination function?

To optimize the PHP code for pagination function, we can limit the number of database queries by retrieving only the necessary data for the current page. This can be achieved by using the LIMIT clause in the SQL query to fetch only the required number of rows. Additionally, we can cache the query results to reduce the overhead of repeated database queries.

// Example of optimized pagination function
function getPaginatedData($page, $limit) {
    $offset = ($page - 1) * $limit;
    
    // Query to fetch data for the current page with LIMIT and OFFSET
    $query = "SELECT * FROM table_name LIMIT $limit OFFSET $offset";
    
    // Check if the query results are cached
    if(!isset($cachedData[$page])) {
        // Execute the query and fetch results
        $result = mysqli_query($connection, $query);
        $data = mysqli_fetch_all($result, MYSQLI_ASSOC);
        
        // Cache the query results
        $cachedData[$page] = $data;
    }
    
    return $cachedData[$page];
}