How can PHP be used to display multiple data entries on a single page, such as 10 entries per page?
To display multiple data entries on a single page, such as 10 entries per page, you can use PHP to retrieve the data from a database and then paginate the results by limiting the number of entries displayed per page. You can achieve this by using SQL queries to fetch a specific range of data based on the page number and the number of entries per page.
<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Define number of entries per page
$entries_per_page = 10;
// Get page number from URL parameter
$page = isset($_GET['page']) ? $_GET['page'] : 1;
// Calculate the starting entry for the query
$start = ($page - 1) * $entries_per_page;
// Fetch data from database
$sql = "SELECT * FROM your_table LIMIT $start, $entries_per_page";
$result = $conn->query($sql);
// Display data entries
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
// Pagination links
$total_entries = 100; // Change this to the total number of entries in your table
$total_pages = ceil($total_entries / $entries_per_page);
for ($i = 1; $i <= $total_pages; $i++) {
echo "<a href='?page=$i'>$i</a> ";
}
$conn->close();
?>