How can PHP developers efficiently manage and display data from a MySQL database without overwhelming the user interface?
To efficiently manage and display data from a MySQL database without overwhelming the user interface, PHP developers can implement pagination. Pagination allows the data to be split into manageable chunks, displaying only a certain number of records per page. This helps improve the user experience by reducing the amount of data shown at once and making navigation easier.
<?php
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Set the number of records to display per page
$records_per_page = 10;
// Get the current page number
if (isset($_GET['page']) && is_numeric($_GET['page'])) {
$page = $_GET['page'];
} else {
$page = 1;
}
// Calculate the starting record for the current page
$start_from = ($page - 1) * $records_per_page;
// Retrieve data from MySQL database with pagination
$query = "SELECT * FROM table_name LIMIT $start_from, $records_per_page";
$result = mysqli_query($connection, $query);
// Display data in HTML table
echo "<table>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['column1'] . "</td>";
echo "<td>" . $row['column2'] . "</td>";
// Add more columns as needed
echo "</tr>";
}
echo "</table>";
// Display pagination links
$query = "SELECT COUNT(*) as total_records FROM table_name";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$total_records = $row['total_records'];
$total_pages = ceil($total_records / $records_per_page);
for ($i = 1; $i <= $total_pages; $i++) {
echo "<a href='?page=$i'>$i</a> ";
}
// Close MySQL connection
mysqli_close($connection);
?>
Keywords
Related Questions
- What is the purpose of using the password_needs_rehash function in PHP for storing password hashes securely in a user database?
- Are there any specific PHP functions or filters that should be used to accurately validate integer values from form inputs?
- What common error occurs when using the unlink() function in PHP?