LoginSignup
3
2

More than 3 years have passed since last update.

PHP 生年月日のselectタグ 値保持

Last updated at Posted at 2020-03-11

生年月日の入力フォームの作り方メモ

selectタグでプルダウンの形で作りました。その際、バリデーションエラー等で元の画面に戻ったときに入力値が保持される様に処理しました。簡単ですがメモしておきます。

まず関数を作ります。

引数に始まりと終わりの年月日を指定し、プルダウンに一覧表示するようにします。第3引数は保持したい値を指定します。
?演算子はとっても便利で、issetで値を確認するときなども良く使います。

function.php
function birthdayLoop($start, $end, $selection=''){
    echo '<option value="">選択してね</option>';
    for($i=$start; $i<=$end; $i++){
        $i = sprintf('%02d', $i);
        $selected = $i==$selection?'selected':'';
        echo "<option value=\"{$i}\" $selected>{$i}</option>";
    }
}

htmlに関数を埋め込みます。

birthday_tpl.php
<label>生年月日</label>
<select name="year">
<?php birthdayLoop('1950', date('Y'), $year); ?> 
</select><select name="month">
<?php birthdayLoop('1', 12, $month); ?> 
</select><select name="day">
<?php birthdayLoop('1',31, $day); ?> 
</select>

バリデーションチェックなどは割愛してます。
最後は3つの変数($year, $month, $day)の値を$birthdayにまとめて代入してDBに保存しました。

極々一般的な処理ですが、値保持のところでつまづきかけたのでメモしておきました(早く初心者脱したいので勉強頑張ります)。

3
2
2

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
3
2