How can database queries be optimized in PHP to avoid mixing with HTML output?

To optimize database queries in PHP and avoid mixing with HTML output, you can separate the database logic from the presentation layer by using a separate PHP file for querying the database and returning the data. Then, in your HTML file, you can include the PHP file using include or require statements to fetch the data and display it without mixing database queries with HTML output.

// database_query.php
<?php
// Database connection and query logic
$connection = mysqli_connect("localhost", "username", "password", "database");
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Fetch and return data
$data = mysqli_fetch_assoc($result);
return $data;
?>

// index.php
<!DOCTYPE html>
<html>
<head>
    <title>Database Query Example</title>
</head>
<body>
    <h1>Data from Database:</h1>
    <?php
    $data = include 'database_query.php';
    echo "<p>Name: " . $data['name'] . "</p>";
    echo "<p>Email: " . $data['email'] . "</p>";
    ?>
</body>
</html>