What best practices should be followed when constructing a dynamic SQL query in PHP based on user input?

When constructing a dynamic SQL query in PHP based on user input, it is crucial to sanitize and validate the input to prevent SQL injection attacks. One way to achieve this is by using prepared statements with parameterized queries. This approach helps separate the SQL query logic from the user input, reducing the risk of malicious code execution.

// Example of constructing a dynamic SQL query using prepared statements
$userInput = $_POST['user_input'];

// Sanitize and validate user input
$filteredInput = filter_var($userInput, FILTER_SANITIZE_STRING);

// Prepare the SQL query with a placeholder for the user input
$stmt = $pdo->prepare("SELECT * FROM table WHERE column = :user_input");

// Bind the sanitized user input to the placeholder in the query
$stmt->bindParam(':user_input', $filteredInput, PDO::PARAM_STR);

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

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

// Process the results as needed
foreach ($results as $row) {
    // Do something with the data
}