When implementing a search feature in PHP using object-oriented programming, what strategies can be employed to ensure efficient and accurate results?
When implementing a search feature in PHP using object-oriented programming, one strategy to ensure efficient and accurate results is to use SQL queries with appropriate indexes on the database columns being searched. Additionally, utilizing pagination can help manage large result sets and improve performance. Lastly, implementing search filters or advanced search options can help users refine their search criteria for more precise results.
```php
// Example PHP code snippet implementing a search feature using object-oriented programming
class Search {
private $db;
public function __construct($db) {
$this->db = $db;
}
public function searchResults($keyword) {
$sql = "SELECT * FROM table_name WHERE column_name LIKE :keyword";
$stmt = $this->db->prepare($sql);
$stmt->execute(array(':keyword' => '%' . $keyword . '%'));
return $stmt->fetchAll();
}
public function searchResultsWithPagination($keyword, $page, $limit) {
$offset = ($page - 1) * $limit;
$sql = "SELECT * FROM table_name WHERE column_name LIKE :keyword LIMIT :limit OFFSET :offset";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':keyword', '%' . $keyword . '%');
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll();
}
public function advancedSearchResults($filters) {
// Build SQL query based on search filters
$sql = "SELECT * FROM table_name WHERE ";
$params = array();
foreach ($filters as $key => $value) {
$sql .= "$key = :$key AND ";
$params[":$key"] = $value;
}
$sql = rtrim($sql, " AND ");
$stmt = $this->db->prepare($sql);
$stmt->execute($params);
return $stmt->fetchAll();
}
}
// Usage example
$search = new Search($db);
$results = $search->searchResults('keyword');
$resultsWithPagination = $search->searchResultsWithPagination('keyword', 1, 10);
$advancedFilters = array('category' => 'books', 'price' => '10');
$advancedResults = $search->advancedSearchResults($advanced