What are best practices for handling user input and database queries in PHP to prevent SQL injection attacks?

SQL injection attacks occur when malicious SQL statements are inserted into input fields, allowing attackers to manipulate databases. To prevent this, use prepared statements with parameterized queries in PHP to sanitize user input and prevent SQL injection attacks.

// Establish a connection to the database
$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 sanitized user input to the parameter
$stmt->bindParam(':username', $_POST['username']);

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

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