1. Start by creating a new folder on your web server to hold your blog files. This folder should be accessible via your website’s URL.
2. Inside this folder, create a new file named “index.php”. This will be the main file for your blog.
3. Open the “index.php” file in a text editor and add the following code to set up the basic structure of a PHP web page:
“`php
“`
4. Next, set up a connection to your database. Create a new file named “config.php” and add the following code:
“`php
connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}
?>
“`
Replace “your_username”, “your_password”, and “your_database_name” with your actual database credentials.
5. In the “index.php” file, add the following code at the top to include the “config.php” file and set up the database connection:
“`php
“`
6. Below the opening `
` tag, add the following code to retrieve and display blog posts from the database:“`php
query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo “
” . $row[“title”] . “
“;
echo “
” . $row[“content”] . “
“;
echo “
Posted on ” . $row[“date”] . “
“;
}
} else {
echo “0 results”;
}
$conn->close();
?>
“`
This code retrieves all posts from the “posts” table in your database and iterates over them, echoing the title, content, and date for each post.
7. Save the “index.php” file and open your website’s URL in a web browser. You should now see a list of blog posts if there are any in the database.
8. To add a new post to the blog, create a new file named “newpost.php” in the blog folder and add the following code:
“`php
query($sql) === TRUE) {
echo “Post created successfully”;
} else {
echo “Error creating post: ” . $conn->error;
}
}
$conn->close();
?>
“`
This code handles the form submission from a “newpost.html” file (which you will create next) and inserts a new post into the “posts” table in the database.
9. Create a new file named “newpost.html” in the blog folder and add the following code:
“`html
New Post
“`
This code creates a simple HTML form with fields for the post title and content. When the form is submitted, it will be sent to the “newpost.php” file for processing.
10. Save all the files and open the “newpost.html” file in a web browser. Fill in the form and click “Create Post”. You should see a confirmation message if the post was successfully created.
11. Finally, add navigation links to your blog by adding the following code inside the `
` tag of the “index.php” file:“`php
My Blog
“`
These links will allow you to navigate to the “newpost.html” file to create a new post, and back to the main blog page.
That’s it! You now have a basic blog setup with PHP. You can continue to enhance it by adding features such as user authentication, comments, categories, etc.