What are the best practices for securely handling user input in PHP when interacting with databases?

When interacting with databases in PHP, it is crucial to securely handle user input to prevent SQL injection attacks. One of the best practices is to use prepared statements with parameterized queries, which separate the SQL code from the user input. This helps to sanitize the input and prevent malicious code from being executed.

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

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

// Bind the user input to the parameter
$stmt->bindParam(':username', $_POST['username']);

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

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