Create and Manage HTML Pages Dynamically with PHP & MySQL

Dynamic web page creation functionality helps to make the HTML content of the web page manageable by the admin/user. The user can create an HTML web page with dynamic content and modify the page content in the future. The HTML web page management feature is mainly used in the web application’s admin panel, which allows the site admin to create/update/delete HTML web pages dynamically.

HTML web page management functionality can be implemented with CRUD operations. PHP CRUD operations can help you to create and manage dynamic HTML pages with MySQL. In this tutorial, we will show you how to generate web pages and manage HTML content dynamically with database using PHP and MySQL.

In this example script, the following functionality will be implemented to build dynamic HTML page management system with PHP and MySQL.

Before getting started to create a CRUD application with dynamic HTML page management, take a look at the file structure.

pages_management_with_php/ ├── index.php ├── addEdit.php ├── userAction.php ├── PageDb.class.php ├── config.php ├── common/ │ └── cms.html ├── pages/ └── assets/ ├── bootstrap/ │ └── bootstrap.min.css ├── css/ │ └── style.css ├── js/ │ ├── tinymce/ │ └── jquery.min.js └── images/ 

Create Database Table

To store page information a table is required in the database. The following SQL creates a pages table with some required fields in the MySQL database.

CREATE TABLE `pages` ( `id` int(11) NOT NULL AUTO_INCREMENT, `page_uri` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `content` text COLLATE utf8_unicode_ci DEFAULT NULL, `created` datetime NOT NULL DEFAULT current_timestamp(), `modified` datetime NOT NULL DEFAULT current_timestamp(), `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Configuration File (config.php)

In the config.php file, common settings and database configuration variables are defined.

 
// Common settings
$pageDir = 'pages'; // Folder path to store page files
$pageExtention = '.html'; // File extension
$list_excerpt_length = 100;

// Database configuration
define('DB_HOST', 'MySQL_Database_Host');
define('DB_USERNAME', 'MySQL_Database_Username');
define('DB_PASSWORD', 'MySQL_Database_Password');
define('DB_NAME', 'MySQL_Database_Name');

// Start session
if(!session_id()) <
session_start();
>

?>

CRUD Handler Class (PageDb.class.php)

The PageDb class is a custom PHP library that handles all the CRUD-related operations (fetch, insert, update, and delete) with MySQL.

/* 
* Page Class
* This class is used for database related (connect, fetch, insert, update, and delete) operations
* @author CodexWorld.com
* @url http://www.codexworld.com
* @license http://www.codexworld.com/license
*/

class PageDb <
private
$dbHost = DB_HOST;
private
$dbUsername = DB_USERNAME;
private
$dbPassword = DB_PASSWORD;
private
$dbName = DB_NAME;
private
$dbTable = 'pages';

function
__construct() <
if(!isset(
$this->db)) <
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
if(
$conn->connect_error) <
die(
"Failed to connect with MySQL: " . $conn->connect_error);
>else <
$this->db = $conn;
>
>
>

/*
* Returns rows from the database based on the conditions
* @param array select, where, order_by, limit and return_type conditions
*/
public function getRows($conditions = array()) <
$sql = 'SELECT ';
$sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
$sql .= ' FROM '.$this->dbTable;
if(
array_key_exists("where",$conditions)) <
$sql .= ' WHERE ';
$i = 0;
foreach(
$conditions['where'] as $key => $value) <
$pre = ($i > 0)?' AND ':'';
$sql .= $pre.$key." = '".$value."'";
$i++;
>
>

if(
array_key_exists("order_by",$conditions)) <
$sql .= ' ORDER BY '.$conditions['order_by'];
>else <
$sql .= ' ORDER BY id DESC ';
>

if(
array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)) <
$sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit'];
>elseif(!
array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)) <
$sql .= ' LIMIT '.$conditions['limit'];
>

$stmt = $this->db->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();

if(
array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all') <
switch(
$conditions['return_type']) <
case
'count':
$data = $result->num_rows;
break;
case
'single':
$data = $result->fetch_assoc();
break;
default:
$data = '';
>
>else <
if(
$result->num_rows > 0) <
while(
$row = $result->fetch_assoc()) <
$data[] = $row;
>
>
>
return !empty(
$data)?$data:false;
>

/*
* Insert data into the database
* @param array the data for inserting into the table
*/
public function insert($data) <
if(!empty(
$data) && is_array($data)) <
if(!
array_key_exists('created',$data)) <
$data['created'] = date("Y-m-d H:i:s");
>
if(!
array_key_exists('modified',$data)) <
$data['modified'] = date("Y-m-d H:i:s");
>

$placeholders = array_fill(0, count($data), '?');

$columns = $values = array();
foreach(
$data as $key=>$val) <
$columns[] = $key;
//$values[] = !empty($val)?$this->db->real_escape_string($val):NULL;
$values[] = !empty($val)?$val:NULL;
>

$sqlQ = "INSERT INTO $this->dbTable> (".implode(', ', $columns).") VALUES (".implode(', ', $placeholders)."); ";
$stmt = $this->db->prepare($sqlQ);

$types = array(str_repeat('s', count($values)));
$params = array_merge($types, $values);

call_user_func_array(array($stmt, 'bind_param'), $params);

$insert = $stmt->execute();
return
$insert?$this->db->insert_id:false;
>else <
return
false;
>
>

/*
* Update data into the database
* @param array the data for updating into the table
* @param array where condition on updating data
*/
public function update($data, $conditions) <
if(!empty(
$data) && is_array($data)) <
if(!
array_key_exists('modified', $data)) <
$data['modified'] = date("Y-m-d H:i:s");
>

$placeholders = array_fill(0, count($data), '?');

$columns = $values = array();
foreach(
$data as $key=>$val) <
$columns[] = $key;
//$values[] = !empty($val)?$this->db->real_escape_string($val):NULL;
$values[] = !empty($val)?$val:NULL;
>

$whr_columns = $whr_values = array();
$where_columns = '';
if(!empty(
$conditions)&& is_array($conditions)) <
foreach(
$conditions as $key=>$val) <
$whr_columns[] = $key;
$whr_values[] = !empty($val)?$this->db->real_escape_string($val):NULL;
>

$where_columns = " WHERE ".implode('=?, ', $whr_columns)."=? ";
>

$sqlQ = "UPDATE $this->dbTable> SET ".implode('=?, ', $columns)."=? $where_columns ";
$stmt = $this->db->prepare($sqlQ);

if(!empty(
$whr_columns)) <
$values_where_arr = array_merge($values, $whr_values);
$types = array(str_repeat('s', count($values_where_arr)));
$params = array_merge($types, $values_where_arr);
>else <
$types = array(str_repeat('s', count($values)));
$params = array_merge($types, $values);
>

call_user_func_array(array($stmt, 'bind_param'), $params);

$update = $stmt->execute();
return
$update?$this->db->affected_rows:false;
>else <
return
false;
>
>

/*
* Delete data from the database
* @param array where condition on deleting data
*/
public function delete($id) <
$sqlQ = "DELETE FROM $this->dbTable> WHERE style="color: #007700">;
$stmt = $this->db->prepare($sqlQ);
$stmt->bind_param("i", $id);
$delete = $stmt->execute();
return
$delete?true:false;
>

public function
isPageExists($title, $id='') <
$sqlQ = "SELECT * FROM $this->dbTable> WHERE LOWER(title)=?";
if(!empty(
$id)) <
$sqlQ .= " AND id != ?";
>
$stmt = $this->db->prepare($sqlQ);

if(!empty(
$id)) <
$stmt->bind_param("si", $title_lwr, $id);
>else <
$stmt->bind_param("s", $title_lwr);
>
$title_lwr = strtolower($title);

$stmt->execute();
$result = $stmt->get_result();
return
$result->num_rows > 0?true:false;
>

public function
generatePageUri($string, $wordLimit = 0) <
$separator = '_';

if(
$wordLimit != 0) <
$wordArr = explode(' ', $string);
$string = implode(' ', array_slice($wordArr, 0, $wordLimit));
>

$quoteSeparator = preg_quote($separator, '#');

$trans = array(
'&.+?;' => '',
'[^\w\d _-]' => '',
'\s+' => $separator,
'('.$quoteSeparator.')+'=> $separator
);

$string = strip_tags($string);
foreach (
$trans as $key => $val) <
$string = preg_replace('#'.$key.'#iu', $val, $string);
>

$string = strtolower($string);

return
trim(trim($string, $separator));
>
>

Pages CRUD Operations with PHP (userAction.php)

Using PHP and MySQL, the userAction.php file performs the CRUD operations with Handler Class ( PageDb.class.php ). The code block is executed based on the requested action.

Add/Edit Page:

Delete Records:

After the data manipulation, the status is stored in SESSION with PHP and redirects to the respective page.

// Include configuration file 
require_once 'config.php';

// Include and initialize Page DB class
require_once 'PageDb.class.php';
$pageDb = new PageDb();

// Set default redirect url
$redirectURL = 'index.php';

if(isset(
$_POST['userSubmit'])) <
// Get form fields value
$id = $_POST['id'];
$title = trim(strip_tags($_POST['title']));
$content = $_POST['content'];

$id_str = '';
if(!empty(
$id)) <
$id_str = '?id='.$id;
>

// Fields validation
$errorMsg = '';
if(empty(
$title)) <
$errorMsg .= '

Please enter title.

'
;
>elseif(
$pageDb->isPageExists($title, $id)) <
$errorMsg .= '

The page with the same title already exists.

'
;
>

if(empty(
$content)) <
$errorMsg .= '

Please enter page content.

'
;
>

// Submitted form data
$pageData = array(
'title' => $title,
'content' => $content
);

// Store the submitted field values in the session
$sessData['userData'] = $pageData;

// Process the form data
if(empty($errorMsg)) <
// Create page file
$page_slug = $pageDb->generatePageUri($title);
$page_file = $page_slug.$pageExtention;

$html_file = 'common/cms.html';
$html_file_content = file_get_contents($html_file);
$html_file_content = str_replace('[PAGE_TITLE]', $title, $html_file_content);
$html_file_content = str_replace('[PAGE_CONTENT]', $content, $html_file_content);

if(!
file_exists($pageDir)) <
mkdir($pageDir, 0777);
>
$filePath = $pageDir.'/'.$page_file;
$create_page_file = file_put_contents($filePath, $html_file_content);

if(
$create_page_file) <
$pageData['page_uri'] = $page_file;
if(!empty(
$id)) <
// Get previous data
$cond = array(
'where' => array(
'id' => $id
),
'return_type' => 'single'
);
$prevPageData = $pageDb->getRows($cond);

// Update page data
$cond = array(
'id' => $id
);
$update = $pageDb->update($pageData, $cond);

if(
$update) <
// Remove old page file
if($prevPageData['page_uri'] !== $page_file) <
$filePath_prev = $pageDir.'/'.$prevPageData['page_uri'];
unlink($filePath_prev);
>

$sessData['status']['type'] = 'success';
$sessData['status']['msg'] = 'Page data has been updated successfully.';

// Remote submitted fields value from session
unset($sessData['userData']);
>else <
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = 'Something went wrong, please try again.';

// Set redirect url
$redirectURL = 'addEdit.php'.$id_str;
>
>else <
// Insert page data
$insert = $pageDb->insert($pageData);

if(
$insert) <
$sessData['status']['type'] = 'success';
$sessData['status']['msg'] = 'Page data has been added successfully.';

// Remote submitted fields value from session
unset($sessData['userData']);
>else <
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = 'Something went wrong, please try again.';

// Set redirect url
$redirectURL = 'addEdit.php'.$id_str;
>
>
>else <
$sessData['status']['msg'] = 'Page creation failed! Please try again.';
>
>else <
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = '

Please fill all the mandatory fields.

'
.$errorMsg;

// Set redirect url
$redirectURL = 'addEdit.php'.$id_str;
>

// Store status into the session
$_SESSION['sessData'] = $sessData;
>elseif((
$_REQUEST['action_type'] == 'delete') && !empty($_GET['id'])) <
$id = base64_decode($_GET['id']);

// Get page data
$cond = array(
'where' => array(
'id' => $id
),
'return_type' => 'single'
);
$pageData = $pageDb->getRows($cond);

// Delete page from database
$delete = $pageDb->delete($id);

if(
$delete) <
// Remove page file
if(!empty($pageData['page_uri'])) <
$filePath = $pageDir.'/'.$pageData['page_uri'];
@
unlink($filePath);
>

$sessData['status']['type'] = 'success';
$sessData['status']['msg'] = 'Page has been deleted successfully.';
>else <
$sessData['status']['type'] = 'error';
$sessData['status']['msg'] = 'Some problem occurred, please try again.';
>

// Store status into the session
$_SESSION['sessData'] = $sessData;
>

// Redirect to the respective page
header("Location:".$redirectURL);
exit();
?>

Bootstrap Library

We will use the Bootstrap library to make the table, form, and buttons look better. You can omit it to use a custom stylesheet for HTML table, form, buttons, and other UI elements.

Include the CSS file of the Bootstrap library.

link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

Page Listing with View & Delete Features (index.php)

Initially, all the pages are retrieved from the database and listed in a tabular format with View, Add, Edit, and Delete options.

// Include configuration file 
require_once 'config.php';

// Retrieve session data
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';

// Get status message from session
if(!empty($sessData['status']['msg'])) <
$statusMsg = $sessData['status']['msg'];
$statusMsgType = $sessData['status']['type'];
unset(
$_SESSION['sessData']['status']);
>

// Include and initialize Page DB class
require_once 'PageDb.class.php';
$pageDb = new PageDb();

// Fetch page data from database
$pages = $pageDb->getRows();
?> if(!empty($statusMsg) && ($statusMsgType == 'success')) ?> div class="col-xs-12"> div class="alert alert-success"> echo $statusMsg; ?> div> div> >elseif(!empty($statusMsg) && ($statusMsgType == 'error')) ?> div class="col-xs-12"> div class="alert alert-danger"> echo $statusMsg; ?> div> div> > ?> div class="row"> div class="col-md-12 head"> h5>Pages h5> div class="float-right"> a href="addEdit.php" class="btn btn-success">i class="plus"> i> New Page a> div> div> table class="table table-striped table-bordered"> thead class="thead-dark"> tr> th width="3%"># th> th width="27%">Title th> th width="36%">Content th> th width="16%">Created th> th width="18%">Action th> tr> thead> tbody> if(!empty($pages)) $count = 0; foreach($pages as $row) $count++; ?> tr> td> echo $count; ?> td> td> echo $row['title']; ?> td> td> $content = strip_tags($row['content']);
echo (
strlen($content)>$list_excerpt_length)?substr($content, 0, $list_excerpt_length).'. ':$content;
?> td> td> echo $row['created']; ?> td> td> a href=" echo $pageDir.'/'.$row['page_uri']; ?>" class="btn btn-outline-primary" target="_blank">view a> a href="addEdit.php?id= echo base64_encode($row['id']); ?>" class="btn btn-outline-warning">edit a> a href="userAction.php?action_type=delete&id= echo base64_encode($row['id']); ?>" class="btn btn-outline-danger" onclick="return confirm('Are you sure to delete?');">delete a> td> tr> > >else ?> tr>td colspan="5">No page(s) found. td> tr> > ?> tbody> table> div>

Create and Update Page Content (addEdit.php)

The addEdit.php handles the page creation and content update form functionality.

The TinyMCE plugin is used to replace textarea input field with WYSIWYG HTML Editor. It allows the user to input the page content with an HTML formatting option.
First, include the jQuery library and TinyMCE plugin library files.

 script src="assets/js/jquery.min.js"> script> script src="assets/js/tinymce/tinymce.min.js"> script>

Initialize the TinyMCE plugin to attach the editor with the HTML element ( page_content ).

script> tinymce.init(< selector: '#page_content', plugins: [ 'lists', 'link', 'image', 'preview', 'anchor', 'visualblocks', 'code', 'fullscreen', 'table', 'code', 'help', 'wordcount' ], toolbar: 'undo redo | formatselect | ' + 'bold italic underline strikethrough | alignleft aligncenter ' + 'alignright alignjustify | bullist numlist outdent indent | ' + 'forecolor backcolor | link image | preview | ' + 'removeformat | help', menubar: 'edit view format help' >); script>

Initially, an HTML form is displayed to allow input data.

// Include configuration file 
require_once 'config.php';

// Retrieve session data
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';

// Get status message from session
if(!empty($sessData['status']['msg'])) <
$statusMsg = $sessData['status']['msg'];
$statusMsgType = $sessData['status']['type'];
unset(
$_SESSION['sessData']['status']);
>

// Get page data
$page_id = '';
$pageData = $userData = array();
if(!empty(
$_GET['id'])) <
$page_id = base64_decode($_GET['id']);

// Include and initialize Page DB class
require_once 'PageDb.class.php';
$pageDb = new PageDb();

// Fetch data from database by row ID
$cond = array(
'where' => array(
'id' => $page_id
),
'return_type' => 'single'
);
$pageData = $pageDb->getRows($cond);
>
$userData = !empty($sessData['userData'])?$sessData['userData']:$pageData;
unset(
$_SESSION['sessData']['userData']);

$actionLabel = !empty($page_id)?'Edit':'Add';

?> if(!empty($statusMsg) && ($statusMsgType == 'success')) ?> div class="col-xs-12"> div class="alert alert-success"> echo $statusMsg; ?> div> div> >elseif(!empty($statusMsg) && ($statusMsgType == 'error')) ?> div class="col-xs-12"> div class="alert alert-danger"> echo $statusMsg; ?> div> div> > ?> div class="row"> div class="col-md-12"> h2> echo $actionLabel; ?> Page h2> div> div class="col-md-9"> form method="post" action="userAction.php"> div class="form-group"> label>Title label> input type="text" class="form-control" name="title" placeholder="Enter page title" value=" echo !empty($userData['title'])?$userData['title']:''; ?>" required=""> div> div class="form-group"> label>Content label> textarea class="form-control" name="content" id="page_content" placeholder="Enter page content here. "> echo !empty($userData['content'])?$userData['content']:''; ?> textarea> div> a href="index.php" class="btn btn-secondary">Back a> input type="hidden" name="id" value=" echo !empty($pageData['id'])?$pageData['id']:''; ?>"> input type="submit" name="userSubmit" class="btn btn-success" value="Submit"> form> div> div>

Conclusion

The Page CRUD functionality is very useful when you want to create HTML pages and manage web pages dynamically. Here we have tried to make the page management CRUD simple, where you can create HTML pages dynamically in PHP. All types of HTML tags and formatting can be added to the page content dynamically with PHP CMS pages management system. Not only the page creation, but also you can update and delete page content dynamically using PHP. This example code helps you to develop a content management system (CMS) with PHP and MySQL.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request