With the rapid growth of the e-commerce industry, building a fully functional PHP online store has become a key goal for developers. Product search and sorting are core features that enhance user experience, allowing customers to quickly find and select products. This article explains how to implement these features in PHP with practical code examples.
Product search allows users to locate specific items easily. The following sections show how to implement this functionality.
<?php $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); } ?>
<form action="search.php" method="get"> <input type="text" name="keyword" placeholder="Enter keyword"> <input type="submit" value="Search"> </form>
<?php if (isset($_GET['keyword'])) { $keyword = $_GET['keyword']; $sql = "SELECT * FROM products WHERE name LIKE '%$keyword%'"; $result = $conn->query($sql); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { echo "Product Name: " . $row['name']. " - Price: " . $row['price'] . "<br>"; } } else { echo "No matching products found"; } } ?>
Product sorting enables users to browse items according to different criteria, improving shopping experience. The following sections demonstrate how to implement sorting in PHP.
<a href="sort.php?sortby=price">Sort by Price</a> <a href="sort.php?sortby=name">Sort by Name</a>
<?php if (isset($_GET['sortby'])) { $sortby = $_GET['sortby']; if ($sortby == 'price') { $sql = "SELECT * FROM products ORDER BY price ASC"; } elseif ($sortby == 'name') { $sql = "SELECT * FROM products ORDER BY name ASC"; } $result = $conn->query($sql); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { echo "Product Name: " . $row['name'] . " - Price: " . $row['price'] . "<br>"; } } else { echo "No matching products found"; } } ?>
By following the steps above, you can implement full product search and sorting functionality in your PHP e-commerce platform. Integrating these features not only enhances user experience but also allows customers to quickly find the products they need.
This article provides a basic implementation example. You can adjust and extend it based on your platform's specific requirements.