How can PDO be used to protect against SQL injection in PHP?

To protect against SQL injection in PHP, you can use PDO (PHP Data Objects) to prepare and execute SQL queries with bound parameters. By using prepared statements, PDO automatically escapes input data, preventing malicious SQL injection attacks.

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

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

// Bind the parameter values to the placeholders
$stmt->bindParam(':username', $username);

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

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