How can PHP developers integrate Ajax queries with PDO for live search functionality?
To integrate Ajax queries with PDO for live search functionality in PHP, developers can create a PHP script that connects to a database using PDO to retrieve search results based on user input. This script can be called asynchronously using Ajax to update search results in real-time without refreshing the page.
<?php
// Include database connection file
include 'db_connection.php';
// Get search term from Ajax request
$searchTerm = $_GET['searchTerm'];
// Prepare SQL statement to search for matching records
$stmt = $pdo->prepare("SELECT * FROM products WHERE name LIKE :searchTerm");
$stmt->bindValue(':searchTerm', '%' . $searchTerm . '%');
$stmt->execute();
// Fetch and return search results as JSON
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
Keywords
Related Questions
- How can PHP developers simplify their code and improve maintainability when handling MySQL queries in functions?
- How can one ensure that numbers are properly formatted before insertion into a database to prevent sorting issues?
- What are potential reasons for receiving "Undefined index" errors in PHP, specifically related to POST data?