-
Notifications
You must be signed in to change notification settings - Fork 0
/
edit-post.php
150 lines (114 loc) · 2.35 KB
/
edit-post.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
<?php
require_once 'lib/common.php';
require_once 'lib/edit-post.php';
require_once 'lib/view-post.php';
session_start();
//Don't non-auth see this screen
if (!isLoggedIn())
{
redirectAndExit('index.php');
}
//Empty defualts
$title=$body='';
// Init database and get handle
$pdo=getPDO();
$postId=null;
if (isset($_GET['post_id']))
{
$post=getPostRow($pdo, $_GET['post_id']);
if ($post)
{
$postId= $_GET['post_id'];
$title = $post['title'];
$body = $post['body'];
}
}
// handle the post operation here
$errors= array();
if ($_POST)
{
// Validate these first
$title = $_POST['post-title'];
if (!$title)
{
$errors[] = 'The post must have a title';
}
$body= $_POST['post-body'];
if(!$body)
{
$errors[]= 'The post must have a body';
}
if(!$errors){
$pdo=getPDO();
// Decide if we are editing or adding
if($postId)
{
editPost($pdo, $title, $body, $postId);
}
else
{
$userId = getAuthUserId($pdo);
$postId= addPost($pdo, $title, $body, $userId);
if ($postId===false)
{
$errors[] = 'Post operation failed';
}
}
}
if (!$errors)
{
redirectAndExit('edit-post.php?post_id=' . $postId);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title> A blog application | New post </title>
<?php> require 'templates/head.php' ?>
</head>
<body>
<?php require 'templates/top-menu.php' ?>
<?php if (isset($_GET['post_id'])): ?>
<h1>Edit post</h1>
<?php else: ?>
<h1>New Post</h1>
<?php endif ?>
<?php if ($errors): ?>
<div class="error box">
<ul>
<?php foreach ($errors as $error): ?>
<li><?php echo $error ?></li>
<?php endforeach ?>
</ul>
</div>
<?php endif ?>
<form method="post" class="post-form user-form">
<div>
<label for="post-title">Title:</label>
<input
id="post-title"
name="post-title"
type="text"
value="<?php echo htmlEscape($title) ?>"
/>
</div>
<div>
<label for="post-body"> Body:</label>
<textarea
id="post-body"
name="post-body"
rows="12"
cols="70"
><?php echo htmlEscape($body) ?></textarea>
</div>
<div>
<input
type="submit"
value="Save post"
/>
<a href="index.php">Cancel</a>
</div>
</form>
</body>
</html>