Categories: Development

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 = "

The is the title

Now its time for a paragraph, many words go here maybe even a link or two.

";

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:

The is the title

Now its time for a paragraph, many words go here maybe even a link or two.

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.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago