How can PHP developers ensure the security of their code when handling user input for MySQL queries?

PHP developers can ensure the security of their code when handling user input for MySQL queries by using prepared statements with parameterized queries. This method helps prevent SQL injection attacks by separating the SQL query logic from the user input data.

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

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

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

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

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