How can PHP developers protect against SQL injections when querying data from a database?

To protect against SQL injections when querying data from a database in PHP, developers should use prepared statements with parameterized queries. This approach allows developers to separate SQL logic from user input, preventing malicious SQL code from being injected into the query.

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

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

// Bind the parameter values to the placeholders
$statement->bindParam(':username', $_POST['username']);

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

// Fetch the results
$results = $statement->fetchAll(PDO::FETCH_ASSOC);

// Use the results as needed
foreach ($results as $result) {
    echo $result['username'] . "<br>";
}