What are best practices for implementing a search function with wildcards in PHP?
Implementing a search function with wildcards in PHP allows users to search for partial matches in a database. One common way to achieve this is by using the SQL LIKE operator along with placeholders for wildcards such as '%' for zero or more characters and '_' for a single character.
// Assuming $searchTerm contains the search term with wildcards
$searchTerm = 'apple%';
// Connect to database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare and execute SQL query
$stmt = $pdo->prepare("SELECT * FROM fruits WHERE name LIKE ?");
$stmt->execute([$searchTerm]);
// Fetch and display results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $result) {
echo $result['name'] . "<br>";
}