What are some recommended approaches for storing and retrieving HTML formatted code in a MySQL database using PHP?

When storing HTML formatted code in a MySQL database using PHP, it is important to properly escape the HTML content to prevent SQL injection and ensure the data is stored correctly. One approach is to use prepared statements with parameter binding to safely insert and retrieve HTML content. Additionally, consider using htmlspecialchars() function when displaying the HTML content to prevent cross-site scripting attacks.

// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

// Prepare and bind a SQL statement for inserting HTML content
$stmt = $conn->prepare("INSERT INTO html_content (content) VALUES (?)");
$stmt->bind_param("s", $html_content);

// Escape the HTML content before storing it in the database
$html_content = htmlspecialchars($html_content);

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

// Close the statement and connection
$stmt->close();
$conn->close();

// Retrieve and display HTML content from the database
$result = $conn->query("SELECT content FROM html_content");
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $html_content = htmlspecialchars_decode($row["content"]);
        echo $html_content;
    }
} else {
    echo "No HTML content found in the database.";
}

// Close the connection
$conn->close();