What is the importance of separating database operations from HTML output in PHP applications?

Separating database operations from HTML output is important in PHP applications to improve code organization, maintainability, and security. By separating these concerns, it makes the code easier to read, maintain, and debug. It also helps prevent SQL injection attacks by properly sanitizing input data before executing database queries.

<?php
// Database operations
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM users";
$result = $conn->query($sql);

// HTML output
echo "<table>";
echo "<tr><th>ID</th><th>Name</th></tr>";

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>" . $row["id"] . "</td><td>" . $row["name"] . "</td></tr>";
    }
} else {
    echo "0 results";
}

echo "</table>";

$conn->close();
?>