0
1

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 3 years have passed since last update.

phpで簡易掲示板を作る

Posted at

・投稿機能のみ
・データ保存先はテキストファイル

index.php
<?php 
//変数定義
$err_msg1 = "";
$err_msg2 = "";
$messsage = "";
$name = (isset($_POST["name"]) === true) ? $_POST["name"]: "";
$comment = (isset($_POST["comment"]) === true) ? ($_POST["comment"]) : "";

//投稿時の処理
if(isset($_POST["submit"]) === true){
    if ($name === "") $err_msg1 = "名前を入力してください";

    if($comment === "") $err_msg2 = "コメントを入力してください";

    if($err_msg1 === "" && $err_msg2 === ""){
        $fp = fopen("data.txt", "a");
        fwrite($fp, $name."\t".$comment."\n");
        $messsage = "書き込みに成功しました。";
    }
}

//表示の処理
$fp = fopen("data.txt","r");
$dataArr = array();
while($res = fgets($fp)){
    $tmp = explode("\t",$res);
    $arr = array(
         "name" => $tmp[0],
         "comment" => $tmp[1]
    );
    $dataArr[] = $arr;
}
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>掲示板</title>
    </head>
    <body>

    <form action="" method="post">
        名前: <input type="text" name="name" value="<?php echo $name; ?>">
        <?php echo $err_msg1; ?><br>
        コメント: <textarea type="textarea" name="comment" rows="4" cols="40"><?php echo $comment; ?></textarea>
        <?php echo $err_msg2; ?><br>
        <input type="submit" name="submit" value="クリック">
    </form>

    <dl>
        <?php foreach ($dataArr as $data): ?>
            <p><span><?php echo $data["name"]; ?></span>:<span><?php echo $data["comment"]; ?></span></p>
        <?php endforeach; ?>
    </dl>
    </body>
</html>
0
1
1

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?