5/22 [PHP] フォームの練習
本日の授業では、PHPによるフォーム作成の実習を行いました。
以下、本日の演習におけるポイントです。
ポイント
- HTML5に対応させる
- placeholder
- required
- autofocus
- encode処理を関数化
- placeholder
- その他
- お問い合わせフォームとアンケートフォームは分けても良い
(理由:アンケートの中に個人情報をあれこれ入力しなければいけないと協力してもらえないかもしれないから)
- お問い合わせフォームとアンケートフォームは分けても良い
【演習】アンケートフォームの作成
1.アンケートフォーム
<!DOCTYPE HTML> <html lang="ja"> <head> <meta charset="utf-8"> <title>入力フォームあれこれ</title> <style> table { border-collapse: collapse; border: 2px solid #95C300; } th, td { border: 1px solid #95C300; padding: 5px 10px; } th { background: #EBF4C9; text-align:center; } td { width: 300px; } </style> </head> <body> <h1>入力フォームあれこれ</h1> <form name="request.php" action="output.php" method="post"> <table> <tr> <th>氏名</th> <td><input type="text" name="name" id="name" size="40" maxlength="20" placeholder="山田太郎" autofocus required></td> </tr> <tr> <th>好きな色</th> <td><select name="color"> <option value="">以下の中から選択してください</option><option value="赤">赤</option><option value="青">青</option><option value="黄色">黄色</option></select></td> </tr> <tr> <th>性別</th> <td><label for="male"><input type="radio" name="gender" id="male" value="男性">男性</label><br><label for="female"><input type="radio" name="gender" id="female" value="女性">女性</label><br><label for="other"><input type="radio" name="gender" id="other" value="回答しない">回答しない</label></td> </tr> <tr> <th>趣味</th> <td><label for="golf"><input type="checkbox" name="hobbies[]" id="golf" value="ゴルフ">ゴルフ</label><br><label for="reading"><input type="checkbox" name="hobbies[]" id="reading" value="読書">読書</label><br><label for="trip"><input type="checkbox" name="hobbies[]" id="trip" value="旅行">旅行</label><br></td> </tr> <tr> <th>自己紹介</th> <td><textarea name="question" cols="40" rows="3" placeholder="初めまして。山田太郎です。よろしくお願いします。"></textarea></td> </tr> </table> <input type="submit" value="送信" class="btn"> </form> </body> </html>
ユーザー定義関数
<?php function enc( $str, $charset ='UTF-8') { return htmlspecialchars($str, ENT_QUOTES, $charset); } ?>
入力結果表示画面
<?php require_once 'Encode.php'; ?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>入力フォームあれこれ</title> <style> table { border-collapse: collapse; border: 2px solid #95C300; } th, td { border: 1px solid #95C300; padding: 5px 10px; } th { background: #EBF4C9; text-align:center; } td { width: 300px; } </style> </head> <body> <h1>入力フォームあれこれ</h1> <p>ご協力ありがとうございました。</p> <table> <tr> <th>氏名</th> <td><?php print (enc($_POST['name'])); ?></td> </tr> <tr> <th>好きな色</th> <td> <?php print (enc($_POST['color'])); ?></td> </tr> <tr> <th>性別</th> <td><?php print (enc($_POST['gender'])); ?></td> </tr> <tr> <th>趣味</th> <td><?php print (enc(implode('、', $_POST['hobbies']))); ?></td> </tr> <tr> <th>自己紹介</th> <td><?php print (nl2br(enc($_POST['question']))); ?></td> </tr> </table> </body> </html>