LoginSignup
1
0

More than 3 years have passed since last update.

PHP 簡単なフォームの作成

Posted at

フォームの作成

今回は簡単な入力フォームを作ります。1ページのみを使用して入力→確認→完了と行いたいと思います。まずはPHPファイルにHTMLを記述します。

index.php
<!DOCTYPE html>
<meta charset="utf-8">
<head></head>
<body>

<form method="POST" action="index.php">
名前
<input type="text" name="your_name">
<br>
メールアドレス
<input type="email" name="email">
<input type="submit" name="btn_confirm" value="送信する">

</form>
</body>
</html>

これでHTMLのみのフォームが出来たかと思います。次に表示の切り替えを行うためにphpを記述します。<!DOCTYPE html>の上に変数を定義したいと思います。

index.php
<?php
$setPage = 0;
?>
<!DOCTYPE html>
<meta charset="utf-8">
<head></head>
<body>

〜以下略〜

<body>の中にもphpを記述します。

index.php
<body>

<?php if($setPage === 0) : ?> //入力画面
入力
<?php endif; ?>

<?php if($setPage === 1) : ?> //確認画面
確認
<?php endif; ?>

<?php if($setPage === 2) : ?> //完了画面
完了
<?php endif; ?>
〜以下略〜

表示の切り替えを変数によって行います。まずは$setPage = 0;の時の表示です。

index.php
<?php if($setPage === 0) : ?> //入力画面
<form method="POST" action="input.php">
名前
<input type="text" name="your_name" >
<br>
メールアドレス
<input type="email" name="email" >
<input type="submit" name="btn_confirm" value="確認する">
</form>
<?php endif; ?>
〜以下略〜

Screenshot from Gyazo

$setPage = 0;の時に表示する入力画面が出来ました。次に$setPage = 1;の処理を記述します。

index.php

<?php

$setPage = 0;

if(!empty($_POST['btn_confirm'])) {
  $setPage = 1;
}

?>
<!DOCTYPE html>
〜以下略〜

if(!empty(~でPOSTの中身が空でなければ$setPage = 1;を表示するというふうに記述します。

index.php

<?php if($setPage === 1) : ?>

<form method="POST" action="input.php">
名前
<?PHP echo $_POST['your_name'] ; ?>
<br>
メールアドレス
<?PHP echo $_POST['email'] ; ?>
<input type="submit" name="btn_submit" value="送信する">

</form>
<?php endif; ?>

〜以下略〜

$setPage = 1;の場合では、$setPage = 0;で入力された値を$_POST(スーパーグローバル変数)で表示しています。
image.png

このような画面になるかと思います。最後に完了画面の表示を行います。

index.php

<?php

$setPage = 0;

if(!empty($_POST['btn_confirm'])) {
  $setPage = 1;
}

if(!empty($_POST['btn_submit'])) {
  $setPage = 2;
}
?>
〜以下略〜

こちらもif(!empty(~で値が空でなければ$setPage = 2;を表示するという処理を記述します。次に<body>の中も記述します。

index.php

<?php if($setPage === 2) : ?>
送信が完了しました。
<?php endif; ?>
〜以下略〜

image.png
このように表示されたかと思います。今回は1つのページで表示を変えるというやり方を行いましたが、別のやり方もあると思いますので、参考程度に利用して頂けたらと思います。なお、スーパーグローバル変数($_POST)など説明していませんが、公式サイト(https://www.php.net/manual/ja/reserved.variables.post.php )を確認していただく方が分かりやすいと思うので今回は割愛します。

最後に

説明などだいぶ端折っているところがありますので、分かりにくい部分もあるかと思います。質問や、ご意見、ご指摘等ありましたらどんどんお願いします!!

1
0
0

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