In the context of PHP functions and SQL queries, what are some best practices for handling dynamic search criteria, such as using placeholders and wildcards?

When handling dynamic search criteria in PHP functions and SQL queries, it is best practice to use placeholders in prepared statements to prevent SQL injection attacks and to properly handle wildcards for flexible searching. By using placeholders, you can bind variables to the query safely and efficiently. Additionally, using wildcards like '%' in conjunction with placeholders allows for more dynamic and flexible search criteria.

// Example of using placeholders and wildcards in a dynamic search query

$searchTerm = "John"; // Dynamic search term

// Prepare the SQL query with a placeholder for the search term
$sql = "SELECT * FROM users WHERE username LIKE ?";
$stmt = $pdo->prepare($sql);

// Bind the search term with wildcard for flexible searching
$searchTerm = '%' . $searchTerm . '%';
$stmt->bindParam(1, $searchTerm, PDO::PARAM_STR);

// Execute the query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Output the results
foreach($results as $result) {
    echo $result['username'] . "<br>";
}