sql >> Databasteknik >  >> RDS >> Mysql

PHP MySQL autoslutförande

Som begärt:

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>

Fippla med console.log istället för platsändring:https://jsfiddle.net/dLe4a83x/



  1. Ansible älskar PostgreSQL

  2. ändra auto_increment inom samma tabell med hjälp av subquery mysql

  3. Hur spolar man performance_schema-statistik utan att starta om MySQL?

  4. PHP mysqli Insert fungerar inte, men ger inga fel