What are the best practices for using PDO prepared statements in PHP to prevent SQL injection?

To prevent SQL injection when using PDO prepared statements in PHP, it is crucial to always use placeholders for user input in SQL queries instead of directly inserting variables. This helps to separate the data from the query, making it impossible for malicious input to alter the query structure. Additionally, make sure to properly sanitize and validate user input before binding it to the prepared statement.

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

// User input
$userInput = $_POST['input'];

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

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

// Execute the prepared statement
$stmt->execute();

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