# 最終状態(仕上げ)

掲示板の完成状態のコードを掲載しておきます。

# index.php

~~/public/index.php

<?php
session_start();
require_once(__DIR__ . '/../src/db_connect.php');

if (isset($_POST['action_type']) && $_POST['action_type']) {
  if ($_POST['action_type'] === 'insert') {
    require(__DIR__ . '/../src/insert_message.php');
  } elseif ($_POST['action_type'] === 'delete') {
    require(__DIR__ . '/../src/delete_message.php');
  }
}

require(__DIR__ . '/../src/session_values.php');

$stmt = $dbh->query('SELECT * FROM posts ORDER BY created_at DESC;');
$message_length = $stmt->rowCount();

function convertTz($datetime_text)
{
  $datetime = new DateTime($datetime_text);
  $datetime->setTimezone(new DateTimeZone('Asia/Tokyo'));
  return $datetime->format('Y/m/d H:i:s');
}
?>
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="robots" content="noindex" />
  <title>ひとこと掲示板</title>
  <link rel="stylesheet" href="./assets/main.css" />
</head>

<body>
  <div class="page-cover">
    <p class="page-title">ひとこと掲示板</p>
    <hr class="page-divider" />

    <?php if ($messages['action_success_text'] !== '') { ?>
      <div class="action-success-area"><?php echo $messages['action_success_text']; ?></div>
    <?php } ?>
    <?php if ($messages['action_error_text'] !== '') { ?>
      <div class="action-failed-area"><?php echo $messages['action_error_text']; ?></div>
    <?php } ?>

    <div class="form-cover">
      <form action="/" method="post">
        <div class="form-input-title">投稿者ニックネーム</div>
        <input type="text" name="author_name" maxlength="40" value="<?php echo htmlspecialchars($messages['input_pre_author_name'], ENT_QUOTES); ?>" class="input-author-name" />
        <?php if ($messages['input_error_author_name'] !== '') { ?>
          <div class="form-input-error">
            <?php echo $messages['input_error_author_name']; ?>
          </div>
        <?php } ?>
        <div class="form-input-title">投稿内容<small>(必須)</small></div>
        <textarea name="message" class="input-message"><?php echo htmlspecialchars($messages['input_pre_message'], ENT_QUOTES); ?></textarea>
        <?php if ($messages['input_error_message'] !== '') { ?>
          <div class="form-input-error">
            <?php echo $messages['input_error_message']; ?>
          </div>
        <?php } ?>
        <input type="hidden" name="action_type" value="insert" />
        <button type="submit" class="input-submit-button">投稿する</button>
      </form>
    </div>
    <hr class="page-divider" />
    <div class="message-list-cover">
      <small>
        <?php echo $message_length; ?> 件の投稿
      </small>

      <?php while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { ?>
        <?php $lines = explode("\n", $row['message']); ?>
        <div class="message-item">
          <div class="message-title">
            <div><?php echo htmlspecialchars($row['author_name'], ENT_QUOTES); ?></div>
            <small><?php echo convertTz($row['created_at']); ?></small>
            <div class="spacer"></div>
            <form action="/" method="post" style="text-align:right">
              <input type="hidden" name="id" value="<?php echo $row['id']; ?>" />
              <input type="hidden" name="action_type" value="delete" />
              <button type="submit" class="message-delete-button">削除</button>
            </form>
          </div>
          <?php foreach ($lines as $line) { ?>
            <p class="message-line"><?php echo htmlspecialchars($line, ENT_QUOTES); ?></p>
          <?php } ?>
        </div>
      <?php } ?>
    </div>
  </div>
</body>

</html>
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

# main.css

~~/src/assets/main.css

@charset "utf-8";
@import url(https://fonts.googleapis.com/css2?family=Roboto:wght@100;300;400;500;700;900&display=swap);
@import url(https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@300;400;500;700;900&display=swap);

/* ===== BASIC BEGIN ===== */
html,
body {
  background-color: #eef3f4;
  font-family: Roboto, 'Noto Sans JP', sans-serif;
  color: #585858;
  margin: 0;
  padding: 0;
}
a {
  color: #3280e7;
  text-decoration: none;
}
a:hover {
  text-decoration: underline;
}
button,
input,
textarea {
  font-family: inherit;
  box-sizing: border-box;
}
button {
  background-color: initial;
  border: initial;
  cursor: pointer;
  outline: initial;
  padding: initial;
  appearance: initial;
  -webkit-appearance: none;
  border-radius: initial;
  font-size: inherit;
}
p {
  margin: 0;
  padding: 0;
}
/* ===== BASIC END ===== */

/* ===== PAGE PARTS BEGIN ===== */
.page-cover {
  max-width: 800px;
  margin: 0 auto;
}
.page-title {
  text-align: center;
  padding: 10px 0;
  margin: 0 auto;
  font-weight: bold;
  font-size: 25px;
}
.page-divider {
  width: 80%;
  max-width: 500px;
  margin: 0 auto 20px auto;
  height: 2px;
  background-color: rgba(0, 0, 0, 0.2);
  border: none;
}
/* ===== PAGE PARTS END ===== */

/* ===== NOTIFICATION AREA BEGIN ===== */
.action-success-area {
  width: max-content;
  margin: 10px auto;
  padding: 5px 15px;
  color: #388e3c;
  border: solid 2px #388e3c;
  border-radius: 4px;
}
.action-failed-area {
  width: max-content;
  margin: 10px auto;
  padding: 5px 15px;
  color: #bb1850;
  border: solid 2px #bb1850;
  border-radius: 4px;
}
/* ===== NOTIFICATION AREA END ===== */

/* ===== NEW MESSAGE FORM AREA BEGIN ===== */
.form-cover {
  margin: 0 auto;
  width: 90%;
}
.form-input-title {
  font-size: 0.875rem;
  padding: 10px;
}
.form-input-error {
  color: #bb1850;
  font-size: 0.875rem;
  padding: 0 10px;
}
.input-author-name {
  font-size: 16px;
  width: 100%;
  height: 2em;
  border: 1px solid rgba(236, 234, 234, 0.5);
  border-radius: 5px;
  box-sizing: border-box;
}
.input-message {
  font-size: 16px;
  width: 100%;
  border: 1px solid rgba(236, 234, 234, 0.5);
  border-radius: 5px;
  height: 100px;
  width: 100%;
  box-sizing: border-box;
  resize: vertical;
  min-height: 100px;
  max-height: 500px;
}
.input-submit-button {
  background-color: #333333;
  border: 2px solid #333333;
  color: #ffffff;
  margin: 15px auto;
  padding: 5px;
  display: block;
  border-radius: 5px;
  width: 100%;
  max-width: 200px;
}
.input-submit-button:hover {
  background-color: #ffffff;
  border: 2px solid #59b1eb;
  color: #59b1eb;
}
/* ===== NEW MESSAGE FORM AREA END ===== */

/* ===== MESSAGE LIST AREA BEGIN ===== */
.message-list-cover {
  margin: 0 auto;
  width: 90%;
}
.message-item {
  background-color: #ffffff;
  margin-bottom: 16px;
  padding: 8px 16px;
  overflow-wrap: break-word;
  border-radius: 4px;
}
.message-title {
  display: flex;
  flex-direction: column;
  gap: 0 10px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  margin-bottom: 4px;
}
.message-title .spacer {
  flex-grow: 1;
}
@media screen and (min-width: 500px) {
  .message-title {
    flex-direction: row;
    align-items: end;
  }
}
.message-line {
  min-height: 1em;
}
.message-delete-button {
  color: #3280e7;
  min-width: max-content;
}
.message-delete-button:hover {
  text-decoration: underline;
}
/* ===== MESSAGE LIST AREA END ===== */
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175

# insert_message

~~/src/insert_message.php

<?php

/**
 * 両端の空白を除去する関数です。マルチバイトを含みます。
 * 参考 https://qiita.com/fallout/items/a13cebb07015d421fde3
 */
function mbTrim($pString)
{
  return preg_replace('/\A[\p{Cc}\p{Cf}\p{Z}]++|[\p{Cc}\p{Cf}\p{Z}]++\z/u', '', $pString);
}

// 入力値を確認する(投稿者)
$is_valid_auther_name = true;
$input_author_name = '';
if (isset($_POST['author_name'])) {
  $input_author_name = mbTrim(str_replace("\r\n", "\n", $_POST['author_name']));
  $_SESSION['input_pre_author_name'] = $_POST['author_name'];
} else {
  $is_valid_auther_name = false;
}

if ($is_valid_auther_name && mb_strlen($input_author_name) > 30) {
  $is_valid_auther_name = false;
  $_SESSION['input_error_author_name'] = 'ニックネームは 30 文字以内で入力してください。(現在 ' . mb_strlen($input_author_name) . ' 文字)';
}

// 入力値を確認する(投稿内容)
$is_valid_message = true;
$input_message = '';
if (isset($_POST['message'])) {
  $input_message = mbTrim(str_replace("\r\n", "\n", $_POST['message']));
  $_SESSION['input_pre_message'] = $_POST['message'];
} else {
  $is_valid_message = false;
}

if ($is_valid_message && $input_message === '') {
  $is_valid_message = false;
  $_SESSION['input_error_message'] = '投稿内容の入力は必須です。';
}

if ($is_valid_message && mb_strlen($input_message) > 1000) {
  $is_valid_message = false;
  $_SESSION['input_error_message'] = '投稿内容は 1000 文字以下で入力してください。(現在 ' . mb_strlen($input_message) . ' 文字)';
}

// 投稿をデータベースへ保存する処理
if ($is_valid_auther_name && $is_valid_message) {
  if ($input_author_name === '') {
    $input_author_name = '匿名さん';
  }

  // INSERT クエリを作成する
  // :author_name、:message はプレースホルダという。後で $stmt->bindValue を使用して値をセットするときのニックネームのようなもの。自分で決められる。
  $query = 'INSERT INTO posts (author_name, message) VALUES (:author_name, :message)';

  // SQL 実行の準備 (実行はされない)
  $stmt = $dbh->prepare($query);

  // プレースホルダに値をセットする
  $stmt->bindValue(':author_name', $input_author_name, PDO::PARAM_STR);
  $stmt->bindValue(':message', $input_message, PDO::PARAM_STR);

  // クエリを実行する
  $stmt->execute();
  $_SESSION['action_success_text'] = '投稿しました';
  $_SESSION['action_error_text'] = '';
  $_SESSION['input_error_author_name'] = '';
  $_SESSION['input_error_message'] = '';
  $_SESSION['input_pre_author_name'] = '';
  $_SESSION['input_pre_message'] = '';
} else {
  $_SESSION['action_success_text'] = '';
  $_SESSION['action_error_text'] = '入力内容を確認してください';
}

header('Location: /');
exit();
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

# delete_message

~~/src/delete_message

<?php

if (isset($_POST['id']) && $_POST['id']) {
  $stmt = $dbh->prepare('DELETE FROM posts WHERE id = :id');
  $stmt->bindValue(':id', $_POST['id'], PDO::PARAM_INT);
  $stmt->execute();
  $_SESSION['action_success_text'] = '削除が完了しました';
  $_SESSION['action_error_text'] = '';
} else {
  $_SESSION['action_success_text'] = '';
  $_SESSION['action_error_text'] = 'id がありません';
}

header('Location: /');
exit();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# session_values.php

~~/src/session_values.php

<?php
// ページ内で使用する変数を初期化する
$messages['action_success_text'] = '';
$messages['action_error_text'] = '';
$messages['input_error_author_name'] = '';
$messages['input_error_message'] = '';
$messages['input_pre_author_name'] = '';
$messages['input_pre_message'] = '';

// ページ内で使用する変数にセッションから代入する
if (isset($_SESSION['action_success_text'])) {
    $messages['action_success_text'] = $_SESSION["action_success_text"];
    unset($_SESSION["action_success_text"]);
}

if (isset($_SESSION['action_error_text'])) {
    $messages['action_error_text'] = $_SESSION["action_error_text"];
    unset($_SESSION["action_error_text"]);
}

if (isset($_SESSION['input_error_author_name'])) {
    $messages['input_error_author_name'] = $_SESSION["input_error_author_name"];
    unset($_SESSION["input_error_author_name"]);
}

if (isset($_SESSION['input_error_message'])) {
    $messages['input_error_message'] = $_SESSION["input_error_message"];
    unset($_SESSION["input_error_message"]);
}

if (isset($_SESSION['input_pre_author_name'])) {
    $messages['input_pre_author_name'] = $_SESSION["input_pre_author_name"];
    unset($_SESSION["input_pre_author_name"]);
}

if (isset($_SESSION['input_pre_message'])) {
    $messages['input_pre_message'] = $_SESSION["input_pre_message"];
    unset($_SESSION["input_pre_message"]);
}
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

# db_connect.php

~~/src/db_connect.php

<?php
try {
    if (getenv('JAWSDB_URL')) {
        // Heorku (JawsDB)
        $_url = parse_url(getenv('JAWSDB_URL'));
        $dbHost = $_url['host'];
        $dbPort = $_url['port'];
        $dbName = ltrim($_url['path'], '/');
        $dbUser = $_url['user'];
        $dbPass = $_url['pass'];
    } else {
        // Other (Local development)
        $dbHost = getenv('DB_HOST');
        $dbPort = getenv('DB_PORT');
        $dbName = getenv('DB_NAME');
        $dbUser = getenv('DB_USER');
        $dbPass = getenv('DB_PASS');
    }
    $dsn = "mysql:dbname=$dbName;host=$dbHost:$dbPort";
    $dbh = new PDO($dsn, $dbUser, $dbPass);
} catch (PDOException $e) {
    echo 'データベース接続失敗:';
    echo $e->getMessage();
    exit();
}
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