How to create a dynamic website with HTML and PHP?

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.
  • 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;
    0 – Specify the extension of the page file (.html/.php).
  • 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;
    1 – Character limit of the content shown in the page list.
  • 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;
    2 – Database host.
  • 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;
    3 – Database username.
  • 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;
    4 – Database password.
  • 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;
    5 – Database name.

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

  • 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;
    6 – Fetch records from the database using PHP and MySQL.
  • 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;
    7 – Insert data into the 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;
    8 – Update existing data in the database based on specified conditions.
  • 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;
    9 – Remove a record from the database by ID.
  • // 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();
    }

    ?>

    0 – Check if a record is existing with the same page title in the database.
  • // 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();
    }

    ?>

    1 – Generate page URL slug from string.
/*
 * 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 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($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

// 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();
}

?>

2 file performs the CRUD operations with Handler Class (

// 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();
}

?>

3). 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 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();
    }

    ?>

    4) 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.

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

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

    // 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();
    }

    ?>

    5 and id params. The page data is deleted from the database based on the unique identifier (id).

Create and Update Page Content (addEdit.php)

The

// 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();
}

?>

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

Initialize the TinyMCE plugin to attach the editor with the HTML element (

// 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();
}

?>

7).

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

Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request

How will you create dynamic HTML from PHP?

You just need to create one php file that generate an html template, what changes is the text based content on that page. In that page is where you can get a parameter (eg. row id) via POST or GET and then get the info form the database.

How to make a dynamic website in PHP?

Creating Dynamic Web Sites with PHP and MySQL.
Using External Files..
Creating and Calling Your Own Functions..
Variable Scope..
Handling HTML Forms with PHP Redux..
Sending Email..
HTTP Headers..
Making Sticky Forms..
Date and Time Functions..

How does PHP and HTML interact in dynamic website development?

PHP codes are dynamic. HTML codes are static. PHP is used for server-side programming which will interact with databases to retrieve information, storing, email sending, and provides content to HTML pages to display on the screen. HTML is used for specifying colors, text formatting, aligning, etc.

How to create a dynamic website in HTML?

Follow these general steps to successfully design and create a dynamic website..
Design the page. A key step in designing any website—whether static or dynamic—is the visual design of the page. ... .
Create a source of dynamic content. ... .
Add dynamic content to a web page. ... .
Add server behaviors to a page. ... .
Test and debug the page..