How can PHP scripts be refactored to separate database queries from HTML output for better code organization?

To separate database queries from HTML output in PHP scripts for better code organization, you can create separate functions or classes to handle database interactions and return data to be used in the HTML output. This helps in keeping the code modular, easier to maintain, and more readable.

// Function to retrieve data from the database
function getDataFromDatabase() {
    // Database connection code
    // Query to retrieve data from the database
    // Return the fetched data
}

// HTML output code
$data = getDataFromDatabase();
// Use $data to display content in HTML