What are the best practices for handling database queries and outputting data in PHP?

When handling database queries in PHP, it is important to use prepared statements to prevent SQL injection attacks and ensure data security. Additionally, always sanitize user input to prevent malicious code execution. Finally, properly handle errors and exceptions to provide meaningful feedback to users.

// Example of handling a database query in PHP using prepared statements and error handling

// 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', $_POST['username']);

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

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

// Handle errors
if (!$results) {
    echo "Error executing query.";
} else {
    foreach ($results as $row) {
        echo $row['username'] . "<br>";
    }
}