Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MySQL autocomplete

Tags:

php

search

mysql

I have an auto complete search field which as the user types a name, th results are shown in the dropdown.

This all works fine, and shows the data as it should.

I am waiting to make each result a link however, so when the results are shown the user can click on the correct name and it will take them to their profile.

See script below:

<input type='text' id=employees class='form-control' size="80" placeholder="Search Employees by first or last name">

search.php

$searchTerm = $_GET['term'];

    $sql = mysql_query ("SELECT name_first, employee_id, unique_id, name_last FROM hr_employees WHERE name_first LIKE '{$searchTerm}%' OR name_first LIKE '{$searchTerm}%' OR employee_id LIKE '{$searchTerm}%'");
    $array = array();
    while ($row = mysql_fetch_array($sql)) {
        $array[] = array (

            'value' => $row['name_first'].' '.$row['name_last'].' ('.$row['employee_id'].')',

        );
    }
    //RETURN JSON ARRAY
    echo json_encode ($array);

Upon selecting the correct user, I would like the user to de directed to page.php?id=$employee_id

Is this possible?

JavaScript

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

JavaScript

<script>
$(function() {
$( "#employees" ).autocomplete({
source: 'search.php'
});
});
</script>
like image 653
Shane Avatar asked Dec 04 '25 16:12

Shane


1 Answers

As requested:

PHP:

$pdo        = new \PDO('mysql:host=localhost;dbname=test', $user, $pass);
$searchTerm = $_GET['term'];

$stmt = $pdo->prepare("SELECT name_first, employee_id, unique_id, name_last FROM hr_employees WHERE name_first LIKE :search OR name_first LIKE :search OR employee_id LIKE :search");
$stmt->execute([':search' => $searchTerm.'%']);

$array = [];
while (false !== ($row = $stmt->fetch())) {
    $array[] = [
        'value' => $row['name_first'].' '.$row['name_last'].' ('.$row['employee_id'].')',
        'id'    => $row['id'],
    ];
}

echo json_encode($array);

JavaScript:

<script>
    $( "#employees" ).autocomplete({
        source: 'search.php',
        select: function( event, ui ) {
          window.location.href = 'page.php?id='+ui.item.id;
        }
    });
</script>

Fiddle with console.log instead of location change: https://jsfiddle.net/dLe4a83x/

like image 67
colburton Avatar answered Dec 06 '25 06:12

colburton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!