Mysql
 sql >> Database >  >> RDS >> Mysql

Completamento automatico PHP MySQL

Come richiesto:

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>

Giocherellare con console.log invece di cambiare posizione:https://jsfiddle.net/dLe4a83x/