Created
August 12, 2023 11:33
-
-
Save aqua-programdiaryblog/8416460e9f055dfa31808baa09540695 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//タイムゾーンを東京に設定 | |
date_default_timezone_set('Asia/Tokyo'); | |
//投稿データの格納用 | |
$posts = array(); | |
//エラーの格納用 | |
$error = array(); | |
//データベース接続 | |
try { | |
$dbh = new PDO('mysql:host=127.0.0.1;dbname=bbs', 'root', ''); | |
}catch(PDOException $e){ | |
echo 'DB接続エラー:' . $e->getMessage(); | |
} | |
//フォームを送信したとき | |
if(!empty($_POST['submitButton'])){ | |
//名前のチェック | |
if(empty($_POST['username'])){ | |
$error['username'] = 'error'; | |
} | |
//コメントのチェック | |
if(empty($_POST['comment'])){ | |
$error['comment'] = 'error'; | |
} | |
if(empty($error)){ | |
$postDate = date('Y-m-d H:i:s'); | |
try { | |
$stmt = $dbh->prepare("INSERT INTO `bbs-table` (`username`, `comment`, `postDate`) VALUES (:username, :comment, :postDate)"); | |
$stmt->bindParam(':username', $_POST['username'], PDO::PARAM_STR); | |
$stmt->bindParam(':comment', $_POST['comment'], PDO::PARAM_STR); | |
$stmt->bindParam(':postDate', $postDate, PDO::PARAM_STR); | |
$stmt->execute(); | |
}catch(PDOException $e){ | |
echo 'DBへの書き込みエラー:' . $e->getMessage(); | |
} | |
} | |
} | |
//DBからコメントデータを取得する | |
$posts = $dbh->prepare('SELECT `id`, `username`, `comment`, `postDate` FROM `bbs-table`'); | |
$posts->execute(); | |
//htmlspecialcharsのショートカット | |
function h($value) { | |
return htmlspecialchars($value, ENT_QUOTES); | |
} | |
//DBの接続を閉じる | |
$dbh = null | |
?> | |
<!DOCTYPE html> | |
<html lang="ja"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>掲示板</title> | |
</head> | |
<body> | |
<h1>掲示板</h1> | |
<hr> | |
<section> | |
<?php foreach($posts as $post): ?> | |
<article> | |
<p>名前 : <?php echo h($post["username"]); ?></p> | |
<p><?php echo h($post["comment"]); ?></p> | |
<time><?php echo h($post["postDate"]); ?></time> | |
</article> | |
<?php endforeach; ?> | |
</section> | |
<form method="post"> | |
<div> | |
<label for="">名前 : </label> | |
<input type="text" name="username"> | |
</div> | |
<div> | |
<textarea name="comment"></textarea> | |
</div> | |
<div> | |
<input type="submit" value="書き込む" name="submitButton"> | |
</div> | |
</form> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment