What is the best practice for securely querying a database in PHP using user input?

When querying a database in PHP using user input, it is crucial to sanitize and validate the input to prevent SQL injection attacks. The best practice is to use prepared statements with parameterized queries, which separate the SQL query from the user input. This helps to ensure that the user input is treated as data rather than executable code.

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Sanitize and validate user input
$userInput = $_POST['input'];
$userInput = filter_var($userInput, FILTER_SANITIZE_STRING);

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM mytable WHERE column = :input");

// Bind the user input to the parameter
$stmt->bindParam(':input', $userInput);

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

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

// Use the results as needed
foreach ($results as $row) {
    // Process each row
}