Manage AD Users users via php script, and notify them on account expiration via e-mail
December 22, 2022How to create a multiboot USB disk
December 27, 2022Creating a blog using PHP and MySQL is a relatively straightforward process that can be accomplished by anyone with a basic understanding of web development. In this tutorial, we will walk you through the steps of setting up a simple blog using PHP and MySQL, complete with code examples and an administration page for managing the blog’s content.
Before we begin, you will need to have a basic understanding of PHP and MySQL, as well as access to a web server that supports these technologies. You will also need a text editor for writing code and a web browser for testing your blog.
Step 1: Setting up the database
The first step in creating a blog using PHP and MySQL is to set up the database that will store all of the blog’s data. To do this, you will need to create a new MySQL database and then create a table within that database to store the blog’s posts.
To create a new MySQL database, open the MySQL command line client or use a graphical tool such as PHPMyAdmin. Then, execute the following SQL statement:
CREATE DATABASE blog;
This will create a new database called “blog”.
Next, we will create a table within the “blog” database to store the blog’s posts. To do this, execute the following SQL statement:
CREATE TABLE posts ( id INT(11) AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255) NOT NULL, content TEXT NOT NULL, date DATETIME NOT NULL );
This will create a table called “posts” with four columns: “id”, “title”, “content”, and “date”. The “id” column is an auto-incrementing primary key, while the “title” and “content” columns are both required and can hold up to 255 and 65535 characters, respectively. The “date” column will store the date and time that each post was created.
Step 2: Connecting to the database with PHP
Once the database has been set up, we can start writing the PHP code that will connect to the database and retrieve the blog’s posts. To do this, we will use the MySQLi extension, which provides an object-oriented interface for interacting with MySQL databases.
First, we need to create a new PHP script called “config.php” and add the following code:
<?php // Database configuration $db_host = 'localhost'; $db_user = 'username'; $db_pass = 'password'; $db_name = 'blog'; // Connect to the database $db = new mysqli($db_host, $db_user, $db_pass, $db_name); // Check for errors if ($db->connect_error) { die('Connect Error (' . $db->connect_errno . ') ' . $db->connect_error); }
This code will create a new MySQLi connection using the configuration parameters at the top of the script. It will then check for any errors that may occur while connecting to the database.
Step 3: Displaying the blog’s posts
Now that we have a connection to the database, we can start retrieving and displaying the blog’s posts. To do this, we will create a new PHP script called “index.php” and add the following code:
<?php // Include the config file include 'config.php'; // Select all posts from the "posts" table, ordered by the "date" column $result = $db->query("SELECT * FROM posts ORDER BY date DESC"); // Check for errors if (!$result) { die('Error: ' . $db->error); } // Fetch all posts as an associative array $posts = $result->fetch_all(MYSQLI_ASSOC); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdn.simplecss.org/simple.min.css"> <link rel="stylesheet" href="custom.css"> <title> Simple Blog</title> </head> <body> <header> <nav> <a href="/">Home</a> <a href="admin.php">Admin Area</a> </nav> <h1>Simple Blog</h1> </header> <main> <?php foreach ($posts as $post): ?> <h2><?php echo $post['title']; ?></h2> <p><?php echo $post['content']; ?></p> <p>Posted on <?php echo $post['date']; ?></p> <?php endforeach; ?> </main> </body> <footer> <p>Simple Blog</p> </footer> </html>
This code includes the “config.php” script to establish a connection to the database, then selects all rows from the “posts” table and orders them by the “date” column in descending order. It then fetches the results as an associative array and stores them in the “$posts” variable.
Finally, the script loops through the “$posts” array and displays the title, content, and date for each post using a PHP foreach loop.
Step 4: Adding a new post
To allow users to add new posts to the blog, we will create a simple form that submits a POST request to a PHP script called “add_post.php”. Add the following code to “admin.php”:
<form action="add_post.php" method="post"> <label for="title">Title:</label><br> <input type="text" id="title" name="title"><br> <label for="content">Content:</label><br> <textarea id="content" name="content"></textarea><br><br> <input type="submit" value="Submit"> </form>
This form includes a text field for the post’s title and a textarea for the post’s content. When the form is submitted, it will send a POST request to “add_post.php” with the form data as the request body.
Next, we will create “add_post.php” and add the following code:
<?php // Include the config file include 'config.php'; // Check if the form was submitted if (isset($_POST['title']) && isset($_POST['content'])) { // Escape the input to prevent SQL injection attacks $title = $db->real_escape_string($_POST['title']); $content = $db->real_escape_string($_POST['content']); // Insert the post into the "posts" table $result = $db->query("INSERT INTO posts (title, content, date) VALUES ('$title', '$content', NOW())"); // Check for errors if (!$result) { die('Error: ' . $db->error); } } // Redirect to the homepage header('Location: index.php');
This script first checks to see if the form was submitted by checking if the “title” and “content” fields are set in the POST request. If the form was submitted, it escapes the input to prevent SQL injection attacks and then inserts the new post into the “posts” table using an INSERT INTO statement. Finally, it redirects the user back to the homepage using the header function.
Step 5: Creating an administration page
To allow the blog’s administrator to manage the blog’s content, we will create an administration page that allows the administrator to edit or delete existing posts.
First, we will create a new PHP script called “admin.php” and add the following code:
<?php // Include the config file include 'config.php'; // Select all posts from the "posts" table $result = $db->query("SELECT * FROM posts ORDER BY date DESC"); // Check for errors if (!$result) { die('Error: ' . $db->error); } // Fetch all posts as an associative array $posts = $result->fetch_all(MYSQLI_ASSOC); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdn.simplecss.org/simple.min.css"> <link rel="stylesheet" href="custom.css"> <title> Simple Blog</title> </head> <body> <header> <nav> <a href="/">Home</a> <a href="admin.php">Admin Area</a> </nav> <h1>Simple Blog</h1> </header> <main> <h2>Add a new post</h2> <form action="add_post.php" method="post"> <label for="title">Title:</label><br> <input type="text" id="title" name="title"><br> <label for="content">Content:</label><br> <textarea id="content" name="content"></textarea><br><br> <input type="submit" value="Submit"> </form> <?php if(!empty($posts)){ ?> <table> <tr> <th>Title</th> <th>Content</th> <th>Date</th> <th>Actions</th> </tr> <?php foreach ($posts as $post): ?> <tr> <td><?php echo $post['title']; ?></td> <td><?php echo $post['content']; ?></td> <td><?php echo $post['date']; ?></td> <td> <a href="edit_post.php?id=<?php echo $post['id']; ?>">Edit</a> <a href="delete_post.php?id=<?php echo $post['id']; ?>">Delete</a> </td> </tr> <?php endforeach; ?> </table> <?php } ?> </main> </body> <footer> <p>Simple Blog</p> </footer> </html>
This code is similar to the code we used to display the blog’s posts on the homepage, except that it also includes a table with columns for the post’s title, content, date, and actions. The actions column includes links to “edit_post.php” and “delete_post.php”, which will allow the administrator to edit or delete the corresponding post.
Next, we will create “edit_post.php” and add the following code:
<?php // Include the config file include 'config.php'; // Check if the form was submitted if (isset($_POST['title']) && isset($_POST['content'])) { // Escape the input to prevent SQL injection attacks $title = $db->real_escape_string($_POST['title']); $content = $db->real_escape_string($_POST['content']); $id = (int)$_POST['id']; // Update the post in the "posts" table $result = $db->query("UPDATE posts SET title='$title', content='$content' WHERE id=$id"); // Check for errors if (!$result) { die('Error: ' . $db->error); } } // Redirect to the admin page header('Location: admin.php');
This script is similar to the “add_post.php” script, except that it updates an existing post using an UPDATE statement instead of inserting a new post. It also includes a hidden input field called “id” that stores the ID of the post being edited.
Finally, we will create “delete_post.php” and add the following code:
<?php // Include the config file include 'config.php'; // Get the post ID from the query string $id = (int)$_GET['id']; // Delete the post from the "posts" table $result = $db->query("DELETE FROM posts WHERE id=$id"); // Check for errors if (!$result) { die('Error: ' . $db->error); } // Redirect to the admin page header('Location: admin.php');
This script gets the post ID from the query string and uses it to delete the corresponding post from the “posts” table using a DELETE FROM statement.
Conclusion
In this tutorial, we have walked you through the steps of creating a simple blog using PHP and MySQL. We have covered how to set up the database, connect to the database with PHP, display the blog’s posts, add new posts, and create an administration page for managing the blog’s content.
Added
– The simple CSS from simplecss.org
To Add
– a login/logout for the admin area
– an actual text editor for the add post form
– improve the edit post script to preview the existing post for which we edit
We hope that this tutorial has been helpful and that you are now able to create your own blog using PHP and MySQL. If you have any questions or comments, please feel free to leave them below.