How can PHP developers ensure the security of user input when retrieving data from a database?

PHP developers can ensure the security of user input when retrieving data from a database by using prepared statements with parameterized queries. This helps prevent SQL injection attacks by separating SQL code from user input, making it impossible for malicious code to be injected into the query.

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

// Prepare a SQL statement 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', $_GET['username']);

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

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