PHP入門によくある、掲示板を作成してみた。

なんとなく最近コーディングしてないんで、
刺激に欠けてきましたんで、
よくある掲示板をコーディングしてみた。

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
<title>ゲストブックだぜ</title>
</head>
<body>
<form action="<?php echo $_SERVER["PHP_SELF"]?>" method="post" >
	<table border="1">
		<tr>
			<td>名前</td>
			<td><input type="text" name="a_name" size="30"></td>
		</tr>
		<tr>
			<td>メアド</td>
			<td><input type="text" name="a_mail" size="30"></td>
		</tr>
		<tr>
			<td>メッセージ</td>
			<td><textarea rows="5" cols="30" name="a_mes"></textarea></td>
		</tr>
		<tr>
			<td colspan="2"><input type="submit" value="書き込む"></td>
		</tr>
	</table>
</form>

<!--データベースへの接続スクリプト -->
<?php 
$sv = "localhost";
$dbname = "guestbook"; 
$user = "root";
$pass = "mysql";

$conn = mysql_connect($sv, $user, $pass) or die("接続エラー");
mysql_select_db($dbname) or die("接続エラー");
?>

<!--メッセージ書き込みスクリプト -->
<?php 
if ($_SERVER["REQUEST_METHOD"] == "POST") {
	$a_name = cnv_dbstr($_POST["a_name"]);
	$a_mail = cnv_dbstr($_POST["a_mail"]);
	$a_mes = cnv_dbstr($_POST["a_mes"]);
	
	if (!empty($a_name) && !empty($a_mes)) {
		$sql = "insert into guestdata(a_name, a_mail, a_mes, a_date) values (";
		$sql .= "'".$a_name."',";
		$sql .= "'".$a_mail."',";
		$sql .= "'".$a_mes."',";
		$sql .= "'".date("Y/m/d H:i:s")."'";
		$sql .= ")";
		
		$res = mysql_query($sql,$conn) or die("データ追加エラー");
		if (res) {
			echo "<p>書き込みOKよん。</p>";
		}
	} else {
		echo "お名前とメッセージを書かない奴に明日はない!!";
	}
}
//HTMLタグの無効化、文字コードの変更、SQL文字列のエスケープをしています。
function cnv_dbstr($string) {
	$string = htmlspecialchars($string);
	if (get_magic_quotes_gpc()) {
		$string = stripcslashes($string);
	}
	$string - mysql_real_escape_string($string);
	return $string;  
}
?>

<!--メッセージ表示スクリプト -->
<?php 
	$sql = "select * from guestdata order by id desc;";
	$res = mysql_query($sql , $conn) or die("データ抽出エラー");
	while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
		echo "<hr>";
		if (!is_null($row["a_mail"])) {
			echo "<a href=\"mailto:" .$row["a_mail"]."\">"
			.$row["a_name"]."</a>";
		}
		else {
			echo $row["a_name"];
		}
		echo "(" .date("Y/m/d H:i", strtotime($row["a_date"])).")";
		echo "<p>" /*. n12br(*/.$row["a_mes"]/*)*/."</p>";
	}
?>
</body>
</html>