How can PHP be optimized for efficient data retrieval and display on a webpage?
To optimize PHP for efficient data retrieval and display on a webpage, you can use techniques such as caching, pagination, and lazy loading. Caching can help reduce the number of database queries by storing frequently accessed data in memory. Pagination can break up large datasets into smaller chunks, improving load times and user experience. Lazy loading allows you to load data only when it is needed, reducing initial page load times.
// Example of implementing pagination in PHP
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;
// Query to retrieve data with pagination
$query = "SELECT * FROM table_name LIMIT $offset, $limit";
$result = mysqli_query($connection, $query);
// Display data on the webpage
while($row = mysqli_fetch_assoc($result)) {
echo $row['column_name'] . "<br>";
}
// Pagination links
$prev = $page - 1;
$next = $page + 1;
echo "<a href='?page=$prev'>Previous</a>";
echo "<a href='?page=$next'>Next</a>";