以下にドロップダウンメニューがあります。
$form = "
<form action='" . htmlentities($_SERVER["PHP_SELF"]) . "' method='post'>
<table>
<tr>
<td><select name='year' id='yearDrop'>
<option value=''></option>
<option value='$getyear[1]'>1</option>
<option value='$getyear[2]'>2</option>
<option value='$getyear[3]'>3</option>
<option value='$getyear[4]'>4</option>
<option value='$getyear[5]'>5</option>
<option value='$getyear[6]'>6</option>
<option value='$getyear[7]'>7</option>
<option value='$getyear[8]'>8</option>
<option value='$getyear[9]'>9</option>
<option value='$getyear[10]'>10</option>
</select></td>
</tr>
</table>
</form>
";
ドロップダウンメニューがフォームのphp変数にあることに注意してください。私の質問は、「上のドロップダウンメニューを表示するためのはるかに優れた短い方法はありますか?」です。たぶん、ある種のループを使用して各値をループし、各オプションに同じvalue
属性を与えることによってですか?
getyear
単純なifステートメントに合わせるために使用したいと思います。
if ($getyear){
echo "year is chosen";
}else{
$errormsg = "You must enter in Student's current Academic Year to Register";
}
アップデート:
<?php
$getyear = (isset($_POST['year'])) ? $_POST['year'] : '';
$errormsg = (isset($errormsg)) ? $errormsg : '';
$min_year = 1;
$max_year = 10;
$years = range($min_year, $max_year); // returns array with numeric values of 1900 - 2012
$yearHTML = '';
$yearHTML .= '<select name="year" id="yearDrop">'.PHP_EOL;
$yearHTML .= '<option value="">Please Select</option>'.PHP_EOL;
foreach ($years as $year) {
$yearHTML .= "<option>$year</option>".PHP_EOL; // if no value attribute, value will be whatever is inside option tag, in this case, $year
}
$yearHTML .= '</select>';
if( (isset($_POST['registerbtn']))){
$getyear = $_POST['year'];
if (!in_array($getyear , $years)){
echo "year is chosen";
}else{
$errormsg = "You must enter in Student's current Academic Year to Register";
}
}
$form = "
<form action='" . htmlentities($_SERVER["PHP_SELF"]) . "' method='post'>
<table>
<tr>
<td></td>
<td id='errormsg'>$errormsg</td>
</tr>
<tr>
<td>Year:</td>
<td>{$yearHTML}</td>
<td><input type='text' name='year' value='$getyear' /></td>
</tr>
<tr>
<td></td>
<td><input type='submit' value='Register' name='registerbtn' /></td>
</tr>
</table>
</form>";
echo $form;
?>