How can PHP developers utilize JSON and fetch in PHP to improve the efficiency of autocomplete features in forms?
To improve the efficiency of autocomplete features in forms, PHP developers can utilize JSON and fetch in PHP to dynamically retrieve data from a server and populate the autocomplete suggestions. By fetching data asynchronously, only the necessary data is loaded when needed, reducing load times and improving user experience.
<?php
// This script fetches data from a database and returns it as JSON
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');
$stmt = $pdo->prepare('SELECT name FROM users WHERE name LIKE :term');
$stmt->execute(['term' => $_GET['term'] . '%']);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
header('Content-Type: application/json');
echo json_encode($results);
?>