AIPT/en/search_suggestions.php

39 lines
1.1 KiB
PHP
Raw Normal View History

2024-10-29 11:42:53 +08:00
<?php
header('Content-Type: application/json');
include '../cms_admin/db_connection.php'; // Include your database connection file
$query = isset($_GET['query']) ? trim($_GET['query']) : '';
$suggestions = [];
if (!empty($query)) {
// Prepare the statement to prevent SQL injection
$stmt = $conn->prepare("SELECT id, title FROM products WHERE title LIKE ? LIMIT 10");
// Add wildcards to the query for partial matching
$search_query = "%" . $query . "%";
$stmt->bind_param('s', $search_query);
// Execute the statement
if ($stmt->execute()) {
$result = $stmt->get_result();
// Fetch the data
while ($row = $result->fetch_assoc()) {
$suggestions[] = [
'title' => htmlspecialchars($row['title']), // Sanitize output to prevent XSS
'url' => 'product_details?id=' . urlencode($row['id'])
];
}
}
// Close the statement
$stmt->close();
}
// Output the JSON-encoded suggestions array
echo json_encode(['suggestions' => $suggestions]);
// Close the database connection
$conn->close();
?>