-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch.php
More file actions
60 lines (51 loc) · 1.95 KB
/
search.php
File metadata and controls
60 lines (51 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
// Include the database connection
include("database.php");
// Define the size mapping
$sizeMapping = [
'XS' => 'Extra Small',
'S' => 'Small',
'M' => 'Medium',
'L' => 'Large',
'XL' => 'Extra Large',
// Add more sizes as necessary
];
// Get the search query from the request
$searchQuery = isset($_GET['query']) ? trim($_GET['query']) : '';
// Initialize an array to hold the results
$results = [];
$suggestions = [];
// Check if the search query is not empty
if (!empty($searchQuery)) {
// Convert size abbreviations in the search query to full names
foreach ($sizeMapping as $abbreviation => $fullName) {
$searchQuery = str_replace($fullName, $abbreviation, $searchQuery);
}
// Prepare a statement to search for products
$stmt = $connect->prepare("SELECT * FROM products WHERE ProductName LIKE ? OR ProductType LIKE ? OR Color LIKE ? OR Size LIKE ?");
$likeQuery = "%" . $searchQuery . "%";
$stmt->bind_param("ssss", $likeQuery, $likeQuery, $likeQuery, $likeQuery);
$stmt->execute();
$result = $stmt->get_result();
// Fetch results
while ($row = $result->fetch_assoc()) {
$results[] = $row;
}
// If no results found, suggest similar products
if (empty($results)) {
// Prepare a statement to find similar products
$stmt = $connect->prepare("SELECT * FROM products WHERE ProductName LIKE ? OR Color LIKE ? OR Size LIKE ?");
$similarQuery = "%" . substr($searchQuery, 0, strlen($searchQuery) - 1) . "%"; // Remove last character for suggestion
$stmt->bind_param("sss", $similarQuery, $similarQuery, $similarQuery);
$stmt->execute();
$result = $stmt->get_result();
// Fetch suggestions
while ($row = $result->fetch_assoc()) {
$suggestions[] = $row;
}
}
}
// Return results as JSON
header('Content-Type: application/json');
echo json_encode(['results' => $results, 'suggestions' => $suggestions]);
?>