<html>
<head>
<meta charset="UTF-8">
<title>簡易掲示板</title>
</head>
<body>
<?php
// データベースへ接続
include "db_vars.php";
$pdo = new PDO($DB_HOST, $DB_USER, $DB_PASS);
// delete_idを受け取ったらデータベースから削除する
if (isset($_POST["delete_id"])) {
$delete_id = $_POST["delete_id"];
$sql = "DELETE FROM bbs WHERE id = :delete_id;";
$stmt = $pdo->prepare($sql);
$stmt -> bindValue(":delete_id", $delete_id, PDO::PARAM_INT);
$stmt -> execute();
}
// contentを受け取ったらデータベースに書き込む
if (isset($_POST["content"])) {
$content = $_POST["content"];
$sql = "INSERT INTO bbs (content, updated_at) VALUES (:content, NOW());";
$stmt = $pdo->prepare($sql);
$stmt -> bindValue(":content", $content, PDO::PARAM_STR);
$stmt -> execute();
}
?>
<h1>簡易掲示板</h1>
<form action="bbs.php" method="post">
<label>投稿内容</label>
<input type="text" name="content">
<button type="submit">送信</button>
</form>
<?php
// データベースからデータを取得する
$sql = "SELECT * FROM bbs ORDER BY updated_at";
$stmt = $pdo->prepare($sql);
$stmt -> execute();
?>
<table border=1 cellpadding=10>
<tr>
<th>id</th>
<th>日時</th>
<th>投稿内容</th>
<th></th>
</tr>
<?php
// 取得したデータを表示する
while ($row = $stmt -> fetch(PDO::FETCH_ASSOC)) {
//print_r($row);
//echo("<br/>");
?>
<tr>
<td><?= $row["id"] ?></td>
<td><?= $row["updated_at"] ?></td>
<td><?= htmlspecialchars($row["content"], ENT_QUOTES, 'UTF-8') ?></td>
<td>
<form action="bbs.php" method="post">
<input type="hidden" name="delete_id" value=<?= $row["id"] ?>>
<button type="submit">削除</button>
</form>
</td>
</tr>
<?php
}
?>
</table>
</body>
</html>