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 = "";
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:
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.
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Some early September spring shots from a bushwalk, It is still too early for wildflowers.
I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…
If you ever needed a simple solution in Laravel to delete an entire directory and…
How to enforce only one user to register or be registered in a Laravel web…