What best practices should be followed when handling database queries in PHP to avoid common pitfalls?

When handling database queries in PHP, it is important to use prepared statements to prevent SQL injection attacks. This involves using parameterized queries to separate SQL code from user input. Additionally, always validate and sanitize user input to ensure data integrity and security.

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

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

// Bind parameters and execute the query
$username = $_POST['username'];
$stmt->bindParam(':username', $username);
$stmt->execute();

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

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