30971-vm/admin/edit_blog.php
Flatlogic Bot f2c0bb39c0 v1
2025-10-16 13:19:27 +00:00

84 lines
2.3 KiB
PHP

<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit();
}
require_once '../db/config.php';
function create_slug($string){
$slug = preg_replace('/[^A-Za-z0-9-]+'/, '-', strtolower($string));
return $slug;
}
$id = $_GET['id'] ?? null;
if (!$id) {
header('Location: blog.php');
exit();
}
$pdo = db();
// Handle form submission for updating the blog post
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_post'])) {
$title = $_POST['title'];
$content = $_POST['content'];
$slug = create_slug($title);
// Check if slug already exists and make it unique
$stmt = $pdo->prepare("SELECT id FROM blog_posts WHERE slug = ? AND id != ?");
$stmt->execute([$slug, $id]);
$i = 1;
$original_slug = $slug;
while($stmt->fetch()){
$slug = $original_slug . '-' . $i++;
$stmt->execute([$slug, $id]);
}
$stmt = $pdo->prepare("UPDATE blog_posts SET title = ?, content = ?, slug = ? WHERE id = ?");
$stmt->execute([$title, $content, $slug, $id]);
header('Location: blog.php');
exit();
}
// Fetch the blog post
$stmt = $pdo->prepare("SELECT * FROM blog_posts WHERE id = ?");
$stmt->execute([$id]);
$post = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$post) {
header('Location: blog.php');
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit Blog Post</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php include 'header.php'; ?>
<div class="container">
<h1>Edit Blog Post</h1>
<form action="edit_blog.php?id=<?php echo $post['id']; ?>" method="post" class="form-container">
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="title" name="title" value="<?php echo htmlspecialchars($post['title']); ?>" required>
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea id="content" name="content" rows="10" required><?php echo htmlspecialchars($post['content']); ?></textarea>
</div>
<button type="submit" name="update_post">Update Post</button>
</form>
</div>
<?php include 'footer.php'; ?>
</body>
</html>