Database (blogdb):
CREATE DATABASE blogdb;
USE blogdb;
CREATE TABLE posts (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255),
content TEXT
);
Add Post (add.php):
<?php
$conn = new mysqli("localhost", "root", "", "blogdb");
if($_SERVER["REQUEST_METHOD"] == "POST"){
$title = $_POST['title'];
$content = $_POST['content'];
$sql = "INSERT INTO posts (title, content) VALUES ('$title', '$content')";
$conn->query($sql);
header("Location: index.php");
}
?>
<form method="post">
Title: <input type="text" name="title" required><br>
Content:<br>
<textarea name="content" required></textarea><br>
<input type="submit" value="Add Post">
</form>
Show Posts (index.php):
<?php
$conn = new mysqli("localhost", "root", "", "blogdb");
$result = $conn->query("SELECT * FROM posts");
while($row = $result->fetch_assoc()){
echo "<h2>".$row['title']."</h2>";
echo "<p>".$row['content']."</p>";
echo "<a href='edit.php?id=".$row['id']."'>Edit</a> | ";
echo "<a href='delete.php?id=".$row['id']."'>Delete</a><hr>";
}
?>
<a href="add.php">Add New Post</a>
Edit Post (edit.php):
<?php
$conn = new mysqli("localhost", "root", "", "blogdb");
if(isset($_GET['id'])){
$id = $_GET['id'];
$post = $conn->query("SELECT * FROM posts WHERE id=$id")->fetch_assoc();
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$title = $_POST['title'];
$content = $_POST['content'];
$id = $_POST['id'];
$conn->query("UPDATE posts SET title='$title', content='$content' WHERE id=$id");
header("Location: index.php");
}
?>
<form method="post">
<input type="hidden" name="id" value="<?php echo $post['id']; ?>">
Title: <input type="text" name="title" value="<?php echo $post['title']; ?>" required><br>
Content:<br>
<textarea name="content" required><?php echo $post['content']; ?></textarea><br>
<input type="submit" value="Update Post">
</form>
Delete Post (delete.php):
<?php
$conn = new mysqli("localhost", "root", "", "blogdb");
if(isset($_GET['id'])){
$id = $_GET['id'];
$conn->query("DELETE FROM posts WHERE id=$id");
}
header("Location: index.php");
?>
Explanation:
- A CRUD project (Create, Read, Update, Delete).
- Blog posts stored in MySQL.
- Admin can manage posts.
Leave a Reply