search.php

mail@pastecode.io avatar
unknown
php
2 months ago
1.8 kB
1
Indexable
Never
<?php
// Database connection and other setup
$hostname = "localhost"; 
$username = "nhatkhang"; 
$password = "872003";
$dbname = "nhatkhang";

$conn = mysqli_connect($hostname, $username, $password, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// print
// print_r($_GET);

// Pagination configuration
$itemsPerPage = isset($_GET['perPage']) ? $_GET['perPage'] : 10; // Default items per page
// printf("%d items per page\n", $itemsPerPage);
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$offset = ($page - 1) * $itemsPerPage;

if (isset($_GET['searchTerm'])) {
    $searchTerm = $_GET['searchTerm'];
    $query = "SELECT * FROM products WHERE product_name LIKE '%$searchTerm%'"; // Assuming 'products' is the table name

    // Count total rows
    $countQuery = "SELECT COUNT(*) AS total FROM products WHERE product_name LIKE '%$searchTerm%'";
    $countResult = mysqli_query($conn, $countQuery);
    $countRow = mysqli_fetch_assoc($countResult);
    $totalRows = $countRow['total'];

    // Calculate total pages
    $totalPages = ceil($totalRows / $itemsPerPage);

    // Adjust offset based on pagination
    $offset = ($page - 1) * $itemsPerPage;

    // Fetch data with pagination
    $queryWithPagination = $query . " LIMIT $offset, $itemsPerPage";
    $result = mysqli_query($conn, $queryWithPagination);
    $suggestions = array();

    while ($row = mysqli_fetch_assoc($result)) {
        $suggestions[] = array(
            'id' => $row['id'],
            'name' => $row['product_name'],
            'price' => $row['price'],
        );
    }

    // Prepare response
    $response = array(
        'suggestions' => $suggestions,
        'totalPages' => $totalPages
    );

    echo json_encode($response);
}

Leave a Comment