What are some best practices for structuring a SQL query in PHP to filter results based on multiple criteria?

When filtering results based on multiple criteria in a SQL query in PHP, it is best practice to use parameterized queries to prevent SQL injection attacks. You can dynamically build the WHERE clause of the query based on the criteria provided by the user. Additionally, make sure to properly sanitize and validate the input to avoid any unexpected behavior.

<?php
// Assuming $criteria is an array of criteria provided by the user
$whereClause = "";
$params = [];
foreach ($criteria as $key => $value) {
    $whereClause .= " AND $key = :$key";
    $params[":$key"] = $value;
}

$sql = "SELECT * FROM table_name WHERE 1=1 $whereClause";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$results = $stmt->fetchAll();
?>