Storing HTML in a MySQL database

How to store HTML in a MySQL database, this is done for purposes such as a blog or CMS where dynamic pages are generated from a database.

The correct MYSQL data type for the HTML code is TEXT, unless you’re creating huge HTML files that are megabytes in size in that case use MEDIUMTEXT.

Here is some small, basic HTML assigned to a variable in PHP:

$html = "<div><h1>The is the title</h1><p>Now its time for a paragraph, many words go here maybe even a <a href='#'>link</a> or two.</p><img src='https://imagelink.com/ourimage.jpg'></div>";

It can be inserted into the database with (PDO):

$insert = $db->prepare('INSERT INTO `html` (`body`) VALUES (?)');
$insert->execute(["$html"]);

Assuming our database assigns it a unique id which is 15 now to create a HTML file containing the HTML code in the database a function can be made and used as:

function create_html($id, $save_as)
{
    global $db;
    $filename = "$save_as.html";
    $select = $db->prepare("SELECT `body` FROM `html` WHERE `id` = :id");
    $select->execute(array(':id' => $id));
    $row = $select->fetch();
    ob_start();
    echo $row['body'];
    $fp = fopen($filename, 'wa+');
    fwrite($fp, ob_get_contents());
    fclose($fp);
    ob_end_flush();
    return "Created $save_as.html for ID: $id";
}

echo create_html(15, 'testfile');

Will create testfile.html which contains:

<div><h1>The is the title</h1><p>Now its time for a paragraph, many words go here maybe even a <a href='#'>link</a> or two.</p><img src='https://imagelink.com/ourimage.jpg'></div>

Make sure to be aware of any special characters and emoji’s that may break storing and retrieving. htmlspecialchars and htmlspecialchars_decode can be of use.