Ever tried scrolling through an endless list of items? Your users don't want that either! Pagination helps break down large datasets into manageable chunks, while searching lets users find what they need fast. Let's dive in and learn how to implement both efficiently in PHP!
Setting Up the Database
We'll assume we have a products
table:
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT NOT NULL,
price DECIMAL(10,2) NOT NULL
);
Fill it with some data for testing.
Connecting to the Database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "your_database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Boom! You're connected!
Implementing Pagination
Pagination helps load only a portion of data at a time. Let's say we show 5 products per page.
Step 1: Get the Total Number of Records
$results_per_page = 5;
$result = $conn->query("SELECT COUNT(id) AS total FROM products");
$row = $result->fetch_assoc();
$total_pages = ceil($row['total'] / $results_per_page);
Step 2: Get the Current Page
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $results_per_page;
Step 3: Fetch Data for the Current Page
$sql = "SELECT * FROM products LIMIT $start, $results_per_page";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo "<p>" . $row['name'] . " - $" . $row['price'] . "</p>";
}
Step 4: Display Pagination Links
for ($i = 1; $i <= $total_pages; $i++) {
echo "<a href='?page=$i'>$i</a> ";
}
Tada! Now, users can navigate through pages.
Implementing Searching
Let's allow users to search by product name.
Step 1: Get the Search Query
$search = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';
Step 2: Modify the SQL Query for Searching
$sql = "SELECT * FROM products WHERE name LIKE '%$search%' LIMIT $start, $results_per_page";
Step 3: Add a Search Form to the UI
<form method="GET">
<input type="text" name="search" placeholder="Search for a product...">
<button type="submit">Search</button>
</form>
Now users can search and paginate like a breeze!
By mastering pagination & searching, you've improved user experience and optimized performance. Now, your website is faster, smarter, and user-friendly!
Pagination ensures data loads efficiently, Searching helps users find what they need fast
Go ahead and implement this in your project!
0 Comments