Tuesday, November 5, 2024

How to Create a CMS in PHP & Bootstrap with a MySQL Database

Example PHP code for a CMS (Content Management System) with add, update, delete CRUD functionality. It also utilizes Bootstrap for styling, AJAX for the CRUD operations and MySQL for the database.

Code to Create a CMS Using PHP

Table Schema: Here’s the schema for the database table posts:

CREATE TABLE posts (
    id INT(11) AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    content TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

index.php:

<!DOCTYPE html>
<html>
<head>
    <title>My CMS</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <h1>My CMS</h1>
        <button type="button" class="btn btn-primary mb-3" data-toggle="modal" data-target="#addPostModal">Add Post</button>
        <div id="postsContainer">
            <!-- Posts will be dynamically loaded here using AJAX -->
        </div>

        <!-- Add Post Modal -->
        <div class="modal fade" id="addPostModal" tabindex="-1" role="dialog" aria-labelledby="addPostModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addPostModalLabel">Add Post</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form id="addPostForm">
                            <div class="form-group">
                                <label for="title">Title</label>
                                <input type="text" class="form-control" id="title" required>
                            </div>
                            <div class="form-group">
                                <label for="content">Content</label>
                                <textarea class="form-control" id="content" rows="3"></textarea>
                            </div>
                            <button type="submit" class="btn btn-primary">Add</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Edit Post Modal -->
        <div class="modal fade" id="editPostModal" tabindex="-1" role="dialog" aria-labelledby="editPostModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="editPostModalLabel">Edit Post</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form id="editPostForm">
                            <input type="hidden" id="editPostId">
                            <div class="form-group">
                                <label for="editTitle">Title</label>
                                <input type="text" class="form-control" id="editTitle" required>
                            </div>
                            <div class="form-group">
                                <label for="editContent">Content</label>
                                <textarea class="form-control" id="editContent" rows="3"></textarea>
                            </div>
                            <button type="submit" class="btn btn-primary">Save Changes</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Delete Post Modal -->
        <div class="modal fade" id="deletePostModal" tabindex="-1" role="dialog" aria-labelledby="deletePostModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="deletePostModalLabel">Delete Post</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" id="deletePostId">
                        <p>Are you sure you want to delete this post?</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-danger" id="deletePostButton">Delete</button>
                    </div>
                </div>
            </div>
        </div>

    </div>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    <script>
        // Load posts on page load
        $(document).ready(function() {
            loadPosts();
        });

        // Add new post
        $('#addPostForm').submit(function(e) {
            e.preventDefault();
            var title = $('#title').val();
            var content = $('#content').val();

            $.ajax({
                url: 'add_post.php',
                type: 'POST',
                data: {
                    title: title,
                    content: content
                },
                success: function(response) {
                    $('#addPostModal').modal('hide');
                    $('#addPostForm')[0].reset();
                    loadPosts();
                }
            });
        });

        // Edit post
        $('#editPostForm').submit(function(e) {
            e.preventDefault();
            var id = $('#editPostId').val();
            var title = $('#editTitle').val();
            var content = $('#editContent').val();

            $.ajax({
                url: 'edit_post.php',
                type: 'POST',
                data: {
                    id: id,
                    title: title,
                    content: content
                },
                success: function(response) {
                    $('#editPostModal').modal('hide');
                    loadPosts();
                }
            });
        });

        // Delete post
        $('#deletePostButton').click(function() {
            var id = $('#deletePostId').val();

            $.ajax({
                url: 'delete_post.php',
                type: 'POST',
                data: {
                    id: id
                },
                success: function(response) {
                    $('#deletePostModal').modal('hide');
                    loadPosts();
                }
            });
        });

        // Load posts
        function loadPosts() {
            $.ajax({
                url: 'get_posts.php',
                type: 'GET',
                success: function(response) {
                    $('#postsContainer').html(response);
                }
            });
        }

        // Open edit post modal
        function openEditModal(id, title, content) {
            $('#editPostId').val(id);
            $('#editTitle').val(title);
            $('#editContent').val(content);
            $('#editPostModal').modal('show');
        }

        // Open delete post modal
        function openDeleteModal(id) {
            $('#deletePostId').val(id);
            $('#deletePostModal').modal('show');
        }
    </script>
</body>
</html>

add_post.php:

<?php
// Database connection
$conn = new mysqli('localhost', 'username', 'password', 'database_name');
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get post data from AJAX request
$title = $_POST['title'];
$content = $_POST['content'];

// Insert new post into the database
$sql = "INSERT INTO posts (title, content) VALUES ('$title', '$content')";
if ($conn->query($sql) === TRUE) {
    echo "Post added successfully!";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

edit_post.php:

<?php
// Database connection
$conn = new mysqli('localhost', 'username', 'password', 'database_name');
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get post data from AJAX request
$id = $_POST['id'];
$title = $_POST['title'];
$content = $_POST['content'];

// Update post in the database
$sql = "UPDATE posts SET title='$title', content='$content' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
    echo "Post updated successfully!";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

delete_post.php:

<?php
// Database connection
$conn = new mysqli('localhost', 'username', 'password', 'database_name');
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get post ID from AJAX request
$id = $_POST['id'];

// Delete post from the database
$sql = "DELETE FROM posts WHERE id=$id";
if ($conn->query($sql) === TRUE) {
    echo "Post deleted successfully!";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

get_posts.php:

<?php
// Database connection
$conn = new mysqli('localhost', 'username', 'password', 'database_name');
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Retrieve posts from the database
$sql = "SELECT * FROM posts ORDER BY created_at DESC";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $id = $row['id'];
        $title = $row['title'];
        $content = $row['content'];
        $created_at = $row['created_at'];

        echo '<div class="card mb-3">';
        echo '<div class="card-body">';
        echo '<h5 class="card-title">' . $title . '</h5>';
        echo '<p class="card-text">' . $content . '</p>';
        echo '<p class="card-text"><small class="text-muted">Created at ' . $created_at . '</small></p>';
        echo '<button class="btn btn-primary" onclick="openEditModal(' . $id . ', \'' . $title . '\', \'' . $content . '\')">Edit</button>';
        echo '<button class="btn btn-danger ml-2" onclick="openDeleteModal(' . $id . ')">Delete</button>';
        echo '</div>';
        echo '</div>';
    }
} else {
    echo 'No posts found.';
}

$conn->close();
?>

Please make sure to replace 'localhost', 'username', 'password', and 'database_name' with your actual database connection details.

Related Articles

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles