What are best practices for handling user input and database queries in PHP when implementing autocomplete features?
When implementing autocomplete features in PHP, it is important to sanitize and validate user input to prevent SQL injection attacks. It is also recommended to use prepared statements for database queries to further protect against malicious input. Additionally, consider implementing caching mechanisms to improve performance when querying the database for autocomplete suggestions.
// Sanitize and validate user input
$search_term = filter_var($_GET['search_term'], FILTER_SANITIZE_STRING);
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');
// Prepare a SQL query using a prepared statement
$stmt = $pdo->prepare("SELECT * FROM table_name WHERE column_name LIKE :search_term");
$stmt->bindValue(':search_term', '%' . $search_term . '%', PDO::PARAM_STR);
$stmt->execute();
// Fetch results and return them as JSON
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);