45 lines
1.4 KiB
PHP
45 lines
1.4 KiB
PHP
![]() |
<?php
|
||
|
header('Content-Type: application/json');
|
||
|
include '../cms_admin/db_connection.php'; // Include your database connection file
|
||
|
|
||
|
// Initialize an empty array for suggestions
|
||
|
$suggestions = [];
|
||
|
|
||
|
if (isset($_GET['query'])) {
|
||
|
// Limit the input length and sanitize the input
|
||
|
$query = substr($_GET['query'], 0, 100);
|
||
|
$query = trim($query);
|
||
|
|
||
|
// Ensure the query is not empty after trimming
|
||
|
if (!empty($query)) {
|
||
|
// Use a prepared statement to prevent SQL injection
|
||
|
$stmt = $conn->prepare("SELECT id, title FROM products WHERE title LIKE CONCAT(?, '%') LIMIT 10");
|
||
|
$stmt->bind_param('s', $query);
|
||
|
|
||
|
// Execute the statement and get the result
|
||
|
if ($stmt->execute()) {
|
||
|
$result = $stmt->get_result();
|
||
|
|
||
|
while ($row = $result->fetch_assoc()) {
|
||
|
$suggestions[] = [
|
||
|
'title' => htmlspecialchars($row['title']), // Prevent XSS
|
||
|
'url' => 'product_details?id=' . urlencode($row['id'])
|
||
|
];
|
||
|
}
|
||
|
} else {
|
||
|
// Handle SQL execution error (optional, you could log the error)
|
||
|
http_response_code(500);
|
||
|
echo json_encode(['error' => 'An error occurred while fetching suggestions.']);
|
||
|
exit;
|
||
|
}
|
||
|
|
||
|
$stmt->close();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
echo json_encode(['suggestions' => $suggestions]);
|
||
|
|
||
|
// Close the database connection
|
||
|
$conn->close();
|
||
|
?>
|