How can PHP developers implement parameterized queries or prepared statements to prevent SQL injection attacks?

SQL injection attacks occur when user input is directly concatenated into SQL queries, allowing malicious users to manipulate the query and potentially access or modify sensitive data. To prevent this, PHP developers should use parameterized queries or prepared statements. These methods separate the SQL query from the user input, ensuring that input is treated as data rather than executable code.

// Using parameterized queries to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

$username = $_POST['username'];
$password = $_POST['password'];

$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();

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