Từng bước làm website động bằng php

Chào mừng đến với In Pakainfo. com tạo trang Web động. Bạn sẽ Từng bước học lập trình web, dễ dàng và rất thú vị. Trang web này gần như cung cấp cho bạn một hướng dẫn lập trình web hoàn chỉnh được trình bày theo cách dễ thực hiện. Mỗi hướng dẫn lập trình web đều có tất cả các ví dụ thực tế với hàm tạo và hàm hủy lập trình web trong tập lệnh php và ảnh chụp màn hình có sẵn

mục lục. php

<?php
$myFileName = "filename.html"; // or .php file  or .css file genrated
$fh = fopen($myFileName, 'w'); // or die("error");  
$stringData = "
<?php include('config.php');?>
<?php include('header.php');?>
<?php include('sidebarmenu.php');?>
<p>
<ul>
<li>how to make a dynamic web pages using php & mysql</li>
<li>php generate html page</li>
<li>how to create dynamic pages in php</li>
<li>how to generate a html page dynamically using php</li>
<li>php dynamic page content</li>
<li>php dynamic website source code</li>
<li>using php to generate html</li>
<li>how to create a dynamic website in php step by step pdf</li>
</ul>
</p>
<?php include('footer.php');?>
";   
fwrite($fh, $stringData);
?>

đầu ra. tên tập tin. html

Tự động Chỉ số này. chạy tệp php để tạo tên tệp. html hoặc tên tệp. php được tạo động

Chức năng tạo trang web động giúp quản trị viên/người dùng quản lý nội dung HTML của trang web. Người dùng có thể tạo một trang web HTML với nội dung động và sửa đổi nội dung trang trong tương lai. Tính năng quản lý trang web HTML chủ yếu được sử dụng trong bảng quản trị của ứng dụng web, cho phép quản trị viên trang tạo/cập nhật/xóa các trang web HTML một cách linh hoạt

Chức năng quản lý trang web HTML có thể được triển khai với các hoạt động CRUD. Các hoạt động CRUD của PHP có thể giúp bạn tạo và quản lý các trang HTML động với MySQL. Trong hướng dẫn này, chúng tôi sẽ chỉ cho bạn cách tạo các trang web và quản lý nội dung HTML động với cơ sở dữ liệu bằng PHP và MySQL

Trong tập lệnh ví dụ này, chức năng sau sẽ được triển khai để xây dựng hệ thống quản lý trang HTML động với PHP và MySQL

  • Lấy dữ liệu trang từ cơ sở dữ liệu và liệt kê chúng trên trang web
  • Tạo trang HTML có nội dung động bằng PHP
  • Thêm và chèn dữ liệu trang vào cơ sở dữ liệu bằng PHP và MySQL
  • Tạo URL động của trang web và cho phép truy cập vào trang web động
  • Chỉnh sửa và cập nhật nội dung trang bằng PHP
  • Xóa dữ liệu trang khỏi cơ sở dữ liệu và tệp HTML khỏi máy chủ

Trước khi bắt đầu tạo ứng dụng CRUD với quản lý trang HTML động, hãy xem cấu trúc tệp

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/

Tạo bảng cơ sở dữ liệu

Để lưu trữ thông tin trang cần có một bảng trong cơ sở dữ liệu. SQL sau đây tạo một bảng pages với một số trường bắt buộc trong cơ sở dữ liệu 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;

Tệp cấu hình (config. php)

Trong tệp config.php, các biến cấu hình cơ sở dữ liệu và cài đặt chung được xác định

  • $pageDir – Chỉ định đường dẫn thư mục nơi các tệp trang sẽ được lưu trữ
  • 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 – Chỉ định phần mở rộng của tệp trang (. 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 – Giới hạn ký tự của nội dung hiển thị trong danh sách trang
  • 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 – Máy chủ cơ sở dữ liệu
  • 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 – Tên người dùng cơ sở dữ liệu
  • 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 – Mật khẩu cơ sở dữ liệu
  • 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 – Tên cơ sở dữ liệu

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

?>

Lớp xử lý CRUD (PageDb. lớp học. php)

Lớp PageDb là một thư viện PHP tùy chỉnh xử lý tất cả các hoạt động liên quan đến CRUD (tìm nạp, chèn, cập nhật và xóa) với 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 – Tìm nạp bản ghi từ cơ sở dữ liệu bằng PHP và 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 – Chèn dữ liệu vào cơ sở dữ liệu
  • 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 – Cập nhật dữ liệu hiện có trong cơ sở dữ liệu dựa trên các điều kiện cụ thể
  • 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 – Xóa bản ghi khỏi cơ sở dữ liệu theo 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 – Kiểm tra xem có tồn tại một bản ghi có cùng tiêu đề trang trong cơ sở dữ liệu không
  • // 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 – Tạo sên URL trang từ chuỗi
/*
 * 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));
    }
}

Trang Hoạt động CRUD với PHP (userAction. php)

Sử dụng PHP và MySQL, tệp

// 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 thực hiện các thao tác CRUD với 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). Khối mã được thực thi dựa trên hành động được yêu cầu

Thêm/Chỉnh sửa Trang

  • Biểu mẫu được gửi bởi userSubmit bằng phương thức POST
  • Truy xuất giá trị của đầu vào (tiêu đề trang và nội dung) bằng phương thức PHP $_POST
  • Xác thực dữ liệu đầu vào với PHP
  • Tạo sên trang từ tiêu đề bằng cách sử dụng phương thức GenerPageUri() của lớp PageDb
  • Lấy bố cục chung từ trang HTML mặc định (____9_______4) sử dụng hàm file_get_contents() trong PHP
  • Thay thế PAGE_TITLE và PAGE_CONTENT bằng dữ liệu trang động bằng PHP
  • Tạo trang HTML động và tạo tệp trên máy chủ bằng hàm PHP file_put_contents()
  • Nếu một ID hiện có được cung cấp, hãy cập nhật dữ liệu trong cơ sở dữ liệu bằng phương thức update() của lớp PageDb. Nếu không, hãy chèn dữ liệu vào cơ sở dữ liệu bằng phương thức insert() của lớp PageDb

Xóa hồ sơ

  • Nếu xóa được yêu cầu trong action_type, hãy xóa dữ liệu trang khỏi cơ sở dữ liệu dựa trên id được cung cấp trong chuỗi truy vấn
  • Xóa các tệp trang khỏi máy chủ bằng hàm PHP unlink()

Sau khi thao tác dữ liệu, trạng thái được lưu trữ trong PHIÊN với PHP và chuyển hướng đến trang tương ứng

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

Thư viện Bootstrap

Chúng tôi sẽ sử dụng thư viện Bootstrap để làm cho bảng, biểu mẫu và nút trông đẹp hơn. Bạn có thể bỏ qua nó để sử dụng biểu định kiểu tùy chỉnh cho bảng HTML, biểu mẫu, nút và các phần tử giao diện người dùng khác

Bao gồm tệp CSS của thư viện Bootstrap

Danh sách trang có tính năng xem và xóa (chỉ mục. php)

Ban đầu, tất cả các trang được lấy từ cơ sở dữ liệu và được liệt kê ở định dạng bảng với các tùy chọn Xem, Thêm, Chỉnh sửa và Xóa

  • Liên kết Thêm chuyển hướng đến addEdit. trang php để thực hiện thao tác tạo trang
  • Liên kết Xem mở tệp trang và hiển thị nội dung HTML
  • Liên kết Chỉnh sửa chuyển hướng đến addEdit. trang php để thực hiện thao tác cập nhật nội dung trang
  • Liên kết Xóa chuyển hướng đến userAction. tệp php có thông số

    // 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 và id. Dữ liệu trang bị xóa khỏi cơ sở dữ liệu dựa trên mã định danh duy nhất (id)

Tạo và cập nhật nội dung trang (addEdit. 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();
}

?>

6 xử lý chức năng biểu mẫu cập nhật nội dung và tạo trang

Plugin TinyMCE được sử dụng để thay thế trường nhập textarea bằng WYSIWYG HTML Editor. Nó cho phép người dùng nhập nội dung trang bằng tùy chọn định dạng HTML
Đầu tiên, bao gồm thư viện jQuery và các tệp thư viện plugin TinyMCE

Khởi tạo plugin TinyMCE để đính kèm trình chỉnh sửa với phần tử HTML (

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

Ban đầu, một biểu mẫu HTML được hiển thị để cho phép nhập dữ liệu

  • Nếu tham số id tồn tại trên URL, dữ liệu trang hiện có sẽ được truy xuất từ ​​​​cơ sở dữ liệu dựa trên ID này và các trường biểu mẫu sẽ được điền sẵn
  • Sau khi gửi biểu mẫu, dữ liệu biểu mẫu được đăng lên userAction. php để chèn/cập nhật nội dung trang trong cơ sở dữ liệu

Hoạt động CRUD PHP với tệp JSON

Phần kết luận

Chức năng Page CRUD rất hữu ích khi bạn muốn tạo các trang HTML và quản lý các trang web một cách linh hoạt. Ở đây chúng tôi đã cố gắng làm cho CRUD quản lý trang trở nên đơn giản, nơi bạn có thể tạo các trang HTML động trong PHP. Tất cả các loại thẻ HTML và định dạng có thể được thêm động vào nội dung trang bằng hệ thống quản lý trang PHP CMS. Không chỉ tạo trang mà bạn còn có thể cập nhật và xóa nội dung trang một cách linh hoạt bằng cách sử dụng PHP. Mã ví dụ này giúp bạn phát triển hệ thống quản lý nội dung (CMS) với PHP và MySQL

Bạn có muốn nhận trợ giúp triển khai hay sửa đổi hoặc nâng cao chức năng của tập lệnh này không?

Chúng ta có thể tạo trang web động bằng PHP không?

PHP và JavaScript đều là ngôn ngữ lập trình tạo ra kết quả động cho các trang web .

Làm thế nào để tạo một trang web động?

Làm theo các bước chung này để thiết kế và tạo thành công một trang web động. .
thiết kế trang. Một bước quan trọng trong việc thiết kế bất kỳ trang web nào—dù tĩnh hay động—là thiết kế trực quan của trang. .
Tạo nguồn nội dung động. .
Thêm nội dung động vào trang web. .
Thêm các hành vi của máy chủ vào một trang. .
Kiểm tra và gỡ lỗi trang

Làm cách nào để tạo một trang web bằng cách sử dụng PHP từng bước?

Đọc tiếp để tìm hiểu cách tạo một trang web PHP theo từng bước. .
Tạo một trang web PHP. tiêu đề. Để tạo một trang web bằng PHP, bạn sẽ cần xây dựng ba trang web. .
Đặt nội dung vào phần thân trang web PHP của bạn. .
Mã trang web PHP đơn giản cho chân trang. .
Kết hợp trang web PHP đơn giản của bạn với nhau

Trang web động trong PHP là gì?

Trang web động là trang web chứa dữ liệu có thể thay đổi hoặc thay đổi được . Nó sử dụng tập lệnh phía máy khách hoặc máy chủ để tạo nội dung có thể thay đổi. Giống như một trang web tĩnh, nó cũng chứa dữ liệu HTML. Trang web động là những trang web thay đổi nội dung hoặc bố cục theo mọi yêu cầu đến máy chủ web.