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.

  • Fetch page data from the database and list them on the web page.
  • Create an HTML page with dynamic content using PHP.
  • Add and insert page data in the database using PHP and MySQL.
  • Create dynamic URL of the webpage and allow access to the dynamic web page.
  • Edit and update page content with PHP.
  • Delete page data from the database and HTML files from the server.

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.

  • $pageDir – Specify the folder path where the page files will be stored.
  • $pageExtention – Specify the extension of the page file (.html/.php).
  • $list_excerpt_length – Character limit of the content shown in the page list.
  • DB_HOST – Database host.
  • DB_USERNAME – Database username.
  • DB_PASSWORD – Database password.
  • DB_NAME – Database name.
<?php 

// 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.

  • getRows() – Fetch records from the database using PHP and MySQL.
  • insert() – Insert data into the database.
  • update() – Update existing data in the database based on specified conditions.
  • delete() – Remove a record from the database by ID.
  • isPageExists() – Check if a record is existing with the same page title in the database.
  • generatePageUri() – Generate page URL slug from string.
<?php 
/*
 * 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(0count($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(0count($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 id=?"
        
$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($wordArr0$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:

  • The form is submitted by userSubmit with the POST method.
  • Retrieve input’s value (page title and content) using PHP $_POST method.
  • Validate input data with PHP.
  • Create page slug from title using generatePageUri() method of PageDb class.
  • Get the common layout from default HTML page (common/cms.html) using file_get_contents() function in PHP.
  • Replace PAGE_TITLE and PAGE_CONTENT with the dynamic page data using PHP.
  • Generate HTML page dynamically and create a file on the server using PHP file_put_contents() function.
  • If an existing ID is supplied, update data in the database using the update() method of the PageDb class. Otherwise, insert data in the database using the insert() method of the PageDb class.

Delete Records:

  • If delete is requested in action_type, remove page data from the database based on the id given in the query string.
  • Remove page files from the server using the PHP unlink() function.

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

<?php 
// 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 .= '<p>Please enter title.</p>';
    }elseif(
$pageDb->isPageExists($title$id)){
        
$errorMsg .= '<p>The page with the same title already exists.</p>';
    }

    if(empty(
$content)){
        
$errorMsg .= '<p>Please enter page content.</p>';
    }
    
    
// 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($pageDir0777);
        }
        
$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'] = '<p>Please fill all the mandatory fields.</p>'.$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.

  • The Add link redirects to the addEdit.php page to perform the page creation operation.
  • The View link opens the page file and displays the HTML content.
  • The Edit link redirects to the addEdit.php page to perform the page content update operation.
  • The Delete link redirects to the userAction.php file with action_type=delete and id params. The page data is deleted from the database based on the unique identifier (id).
<?php 
// 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();
?> <!-- Display status message --> <?php if(!empty($statusMsg) && ($statusMsgType == 'success')){ ?> <div class="col-xs-12"> <div class="alert alert-success"><?php echo $statusMsg?></div> </div> <?php }elseif(!empty($statusMsg) && ($statusMsgType == 'error')){ ?> <div class="col-xs-12"> <div class="alert alert-danger"><?php echo $statusMsg?></div> </div> <?php ?> <div class="row"> <div class="col-md-12 head"> <h5>Pages</h5> <!-- Add link --> <div class="float-right"> <a href="addEdit.php" class="btn btn-success"><i class="plus"></i> New Page</a> </div> </div> <!-- List the pages --> <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> <?php if(!empty($pages)){ $count 0; foreach($pages as $row){ $count++; ?> <tr> <td><?php echo $count?></td> <td><?php echo $row['title']; ?></td> <td>                     <?php 
                        $content 
strip_tags($row['content']);
                        echo (
strlen($content)>$list_excerpt_length)?substr($content0$list_excerpt_length).'...':$content;
                    
?> </td> <td><?php echo $row['created']; ?></td> <td> <a href="<?php echo $pageDir.'/'.$row['page_uri']; ?>" class="btn btn-outline-primary" target="_blank">view</a> <a href="addEdit.php?id=<?php echo base64_encode($row['id']); ?>" class="btn btn-outline-warning">edit</a> <a href="userAction.php?action_type=delete&id=<?php echo base64_encode($row['id']); ?>" class="btn btn-outline-danger" onclick="return confirm('Are you sure to delete?');">delete</a> </td> </tr> <?php } }else{ ?> <tr><td colspan="5">No page(s) found...</td></tr> <?php ?> </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.

<!-- jQuery library -->
<script src="assets/js/jquery.min.js"></script>

<!-- TinyMCE plugin library -->
<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.

  • If the id parameter exists on the URL, the existing page data will be retrieved from the database based on this ID and the form fields will be pre-filled.
  • After the form submission, the form data is posted to the userAction.php file to insert/update the page content in the database.
<?php 
// 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';

?> <!-- Display status message --> <?php if(!empty($statusMsg) && ($statusMsgType == 'success')){ ?> <div class="col-xs-12"> <div class="alert alert-success"><?php echo $statusMsg?></div> </div> <?php }elseif(!empty($statusMsg) && ($statusMsgType == 'error')){ ?> <div class="col-xs-12"> <div class="alert alert-danger"><?php echo $statusMsg?></div> </div> <?php ?> <div class="row"> <div class="col-md-12"> <h2><?php 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="<?php 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..."><?php echo !empty($userData['content'])?$userData['content']:''?></textarea> </div> <a href="index.php" class="btn btn-secondary">Back</a> <input type="hidden" name="id" value="<?php echo !empty($pageData['id'])?$pageData['id']:''?>"> <input type="submit" name="userSubmit" class="btn btn-success" value="Submit"> </form> </div> </div>

PHP CRUD Operations with JSON File

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

Leave a reply

keyboard_double_arrow_up