Are there any potential pitfalls to be aware of when fetching data from a database in PHP?

One potential pitfall when fetching data from a database in PHP is SQL injection attacks, where malicious code is inserted into SQL statements. To prevent this, you should always use prepared statements with parameterized queries to sanitize user input.

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "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', $_POST['username']);

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

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

// Loop through the results
foreach ($results as $row) {
    // Process the data
}