How can PHP be used to generate multiple pages of data from a database with a set number of entries per page?
To generate multiple pages of data from a database with a set number of entries per page, you can use PHP to query the database for the total number of entries, calculate the total number of pages based on the desired number of entries per page, and then use pagination to display the data accordingly.
<?php
// Connect to your database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');
// Query to get total number of entries
$totalEntries = $pdo->query("SELECT COUNT(*) FROM your_table")->fetchColumn();
$entriesPerPage = 10; // Set the number of entries per page
$totalPages = ceil($totalEntries / $entriesPerPage);
// Get the current page number from the URL
$page = isset($_GET['page']) ? $_GET['page'] : 1;
// Calculate the offset for the query
$offset = ($page - 1) * $entriesPerPage;
// Query to retrieve data for the current page
$stmt = $pdo->prepare("SELECT * FROM your_table LIMIT :offset, :entriesPerPage");
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->bindParam(':entriesPerPage', $entriesPerPage, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetchAll();
// Display the data
foreach ($data as $row) {
// Display data here
}
// Display pagination links
for ($i = 1; $i <= $totalPages; $i++) {
echo "<a href='?page=$i'>$i</a> ";
}
?>