Skip to content
PHP Logo

How can PHP be optimized to handle duplicate entries in a database when using autocomplete?

When handling autocomplete functionality in PHP, one common issue is dealing with duplicate entries in the database. To optimize this, you can use the DISTINCT keyword in your SQL query to ensure that only unique results are returned. Additionally, you can use PHP functions like array_unique() to remove any duplicate entries from the autocomplete suggestions before displaying them to the user.

php
// Assuming $searchTerm is the input from the autocomplete search field
$searchTerm = $_POST['searchTerm'];

// Query to fetch unique results from the database
$query = "SELECT DISTINCT column_name FROM table_name WHERE column_name LIKE '%$searchTerm%'";
$result = mysqli_query($conn, $query);

// Fetch and display autocomplete suggestions
$autocompleteResults = array();
while ($row = mysqli_fetch_assoc($result)) {
    $autocompleteResults[] = $row['column_name'];
}

// Remove any duplicate entries
$autocompleteResults = array_unique($autocompleteResults);

// Output autocomplete suggestions
echo json_encode($autocompleteResults);