What are common pitfalls to avoid when retrieving data from a database using PHP?

One common pitfall to avoid when retrieving data from a database using PHP is not properly sanitizing user input, which can leave your application vulnerable to SQL injection attacks. To prevent this, always use prepared statements with parameterized queries to safely retrieve data from the database.

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

// Prepare a statement with a parameterized query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the parameter value
$stmt->bindParam(':username', $_GET['username']);

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

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

// Loop through the results
foreach ($results as $row) {
    echo $row['username'] . '<br>';
}