What are common pitfalls when selecting values from a database in PHP?

One common pitfall when selecting values from a database in PHP is not properly sanitizing user input, which can lead to SQL injection attacks. To prevent this, you should always use prepared statements or parameterized queries to securely interact with the database. Another pitfall is not handling errors properly, which can result in unexpected behavior or security vulnerabilities.

// Example of selecting values from a database using prepared statements

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

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

// Bind parameters
$stmt->bindParam(':username', $username, PDO::PARAM_STR);

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

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

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