13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでシンプルな掲示板を製作

Last updated at Posted at 2018-04-26

PHPで単純な掲示板を製作。idで降順(最新が上位にくる)になるように、またリロード時の二重投稿への対策はしています。

データベースlocaldbのuserテーブルのデータはid(A_I), name, commentのみです。

index.php
<!DOCTYPE HTML>
<html lang="ja">

<head>
</head>

<body>
	<form method="post" action="">
		<input type="text" name="name" value="">
		<input type="text" name="comment" value="">
		<input type="submit" name="regist" value="登録">
	</form>
</body>
<?php
?>
</html>
php
<?php
	$host = 'localhost:8889';
	$dbname = 'localdb';
	$dbuser = 'root';
	$dbpassword = 'root';
	$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8","$dbuser","$dbpassword");
	#データベースへの登録
	if( isset($_POST['regist']) ){
    	$name = $_POST['name'];
		$comment = $_POST['comment'];
		$sql = "INSERT INTO user (name, comment) VALUES ('$name', '$comment')";
		$res = $pdo->query($sql);
	}
	#テーブル内容の表示
	$sql = "SELECT * FROM user ORDER BY id DESC";
	$stmt = $pdo->query($sql);
	foreach ($stmt as $row) {
		echo $row['name'].' '.$row['comment'];
		echo '<br>';
	}
	#リロード時の二重投稿を防止
	if($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Location:http://localhost:8888/index.php', true, 303);
	}
	#終了
	$stmt = null;
	$pdo = null;
?>

php部分を改訂してみました。 vol.1

php
<?php
	$host = 'localhost:8889';
	$dbname = 'localdb';
	$dbuser = 'root';
	$dbpassword = 'root';
	$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8","$dbuser","$dbpassword");
	#データベースへの登録
	if( isset($_POST['regist']) ){
    	$name = $_POST['name'];
		$comment = $_POST['comment'];
		$stmt = $pdo -> prepare("INSERT INTO user (name, comment) VALUES (:name, :comment)");
		$stmt->bindParam(':name', $name, PDO::PARAM_STR);
		$stmt->bindParam(':comment', $comment, PDO::PARAM_STR);
		$stmt->execute();
		$pdo->query($stmt);
		header("Location: " . $_SERVER['PHP_SELF']);
	}
	#テーブル内容の表示
	$sql = "SELECT * FROM user ORDER BY id DESC";
	$stmt = $pdo->query($sql);
	foreach ($stmt as $row) {
		echo htmlspecialchars($row['name'], ENT_QUOTES|ENT_HTML5).' '.htmlspecialchars($row['comment'], ENT_QUOTES|ENT_HTML5);
		echo '<br>';
	}
?>
13
13
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?