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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago