What are the best practices for handling user input in PHP to prevent SQL-Injection?

To prevent SQL-Injection in PHP, it is essential to sanitize and validate user input before using it in database queries. The best practice is to use prepared statements with parameterized queries, which separate the SQL code from the user input, preventing malicious code from being executed.

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

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

// Prepare a statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $filteredInput);
$stmt->execute();

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