How can one optimize PHP scripts to handle long search queries, especially when accessing a large library database?
To optimize PHP scripts to handle long search queries when accessing a large library database, one can implement pagination to limit the number of results fetched at a time. This helps reduce the strain on the server and improves the script's performance. Additionally, using indexes on frequently searched columns in the database can speed up query execution.
// Set the number of results to display per page
$results_per_page = 10;
// Calculate the offset based on the current page number
if (isset($_GET['page'])) {
$page = $_GET['page'];
} else {
$page = 1;
}
$offset = ($page - 1) * $results_per_page;
// Query the database with pagination
$query = "SELECT * FROM library_table LIMIT $offset, $results_per_page";
$result = mysqli_query($connection, $query);
// Display the results
while ($row = mysqli_fetch_assoc($result)) {
// Display each result
}
// Add pagination links
$total_results = // Query to get total number of results
$total_pages = ceil($total_results / $results_per_page);
for ($i = 1; $i <= $total_pages; $i++) {
echo "<a href='search.php?page=$i'>$i</a>";
}