Building your own Content Management System with PHP and MySQL

Building a Content Management System (CMS) from scratch can be a challenging yet rewarding endeavor. It gives you the freedom to create a system tailored specifically to your needs. This tutorial will guide you through the basic steps of creating a simple CMS using PHP and MySQL.

Prerequisites: Familiarity with PHP programming, MySQL, and a basic understanding of HTML and CSS.

Required Tools: A local server environment (like XAMPP, WAMP, or MAMP), text editor, and a web browser.

Step 1: Setting Up the Database

  1. Launch your MySQL database (via phpMyAdmin or your preferred method).
  2. Create a new database and name it ‘simple_cms’.
  3. In the ‘simple_cms’ database, create a new table named ‘content’ with the following fields:
  • ‘id’ (INT, primary key, auto-increment)
  • ‘title’ (VARCHAR)
  • ‘body’ (TEXT)

Step 2: Establishing a Database Connection

In your project directory, create a new file named ‘config.php’. This file will hold the details of your database connection. Here’s a basic setup:

<?php
$dbhost = 'localhost';
$dbname = 'simple_cms';
$dbuser = 'root';
$dbpass = ''; // adjust this to your local server settings

try {
    $db = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass);
} catch (PDOException $e) {
    echo $e->getMessage();
}
?>

Step 3: Creating a Form to Input Content

In the ‘index.php’ file, create a simple form to input content:

<form action="save_content.php" method="post">
    <label for="title">Title:</label>
    <input type="text" id="title" name="title">

    <label for="body">Content:</label>
    <textarea id="body" name="body"></textarea>

    <input type="submit" value="Submit">
</form>

Step 4: Saving Form Input to the Database

Create a ‘save_content.php’ file. This PHP script will handle the form submission and save the data to the database.

<?php
require_once('config.php');

$title = $_POST['title'];
$body = $_POST['body'];

$sql = "INSERT INTO content (title, body) VALUES (?, ?)";
$query = $db->prepare($sql);
$query->execute(array($title, $body));

header("Location: index.php");
exit;
?>

Step 5: Displaying the Content

Back in ‘index.php’, retrieve and display the saved content:

<?php
require_once('config.php');

$sql = "SELECT * FROM content ORDER BY id DESC";
$query = $db->query($sql);

while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
    echo '<h2>' . $row['title'] . '</h2>';
    echo '<p>' . $row['body'] . '</p>';
}
?>

With these steps, you have created a very basic CMS. You can create new content, and it will be displayed on your page. This is a simple starting point, and there’s much more to add to create a fully-fledged CMS, like user authentication, image uploads, content editing, and deletion, etc. Happy coding!