LoginSignup
9
4

More than 5 years have passed since last update.

新人プログラマがPHPを勉強する(入力フォーム編)

Posted at

HTMLやCSSを一通り勉強して、今度はPHPを覚えたいと思ったのでメモ。全て独学なので、間違えていたら指摘お願いします。

PHPでフォームからデータを受け取る

https://gyazo.com/df3213ed15d1800847415ec716fab833

フォームからのデータの受け取り方法は「GET」と「POST」がある。今回は「POST」について。ファイルはHTMLとPHPの2つを用意する。

HTML

test.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>入力フォーム</title>
</head>
<body>
    <form method="post" action="test.php">
        あなたの名前は?:
        <input type="text" name="name" required>
        <input type="submit" value="送信">
    </form>
</body>
</html>

PHP

test.php
<?php
print_r($_POST);
?>

コードの説明

test.html
<form method="post" action="test.php">
  • 「method(メソッド)」で入力データの受け渡し方として「post」を指定する
  • 「action」でデータ送り先のPHPファイルの名前を指定する
test.html
<input type="text" name="name" required>
  • 「input type="text"」一行テキストボックスを作成する
  • 「type」を「text」にすることで、テキストの入力欄になる
  • 「required(リクワイアード)」で入力必須の項目として指定する
test.html
<input type="submit" value="送信">
  • 「input type="submit"」送信ボタンを作成する
  • 「value」ボタンに表示されるテキストを指定する
test.php
print_r($_POST);

関数 = print_r → 定められた処理を実行
引数 = ($_POST); → 何を・どんな処理をするのかを記述

  • 「print_r」続く()の内容を見やすい形で表示する
  • 「($_POST);」test.htmlのフォームで入力されたデータが格納される

URL

送信ボタンを押すと、htmlファイルからphpファイルにデータを渡せていることがわかる。

▼送信ボタン クリック前「test.html」
https://gyazo.com/4753b4e98018bb37c056a689f8299261

▼送信ボタン クリック後「test.php」
https://gyazo.com/c1b51e646d8c890a256ebe11330b1a26

9
4
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
9
4