PHP drop down menu - php

I want to get values of the selected items from 3 drop down menus ( years , month and day) using PHP ,
I tried this but didn't work
<p><font size="6"> <b>TP3</b></font></p>
<p>
</p>
<table align="center" width="800" border="1" cellspacing="2" cellpadding="2">
<tr>
<td><p><?php echo "Date : " . date("Y/m/d") . "<br>";?></p><br/>
<?php $date = new DateTime();
$day = $date->format('d');
$month = $date->format('m');
$year = $date->format('Y'); ?>
<select name="day">
<option value="day" selected="selected">Day</option>
<?php
for($i=1; $i<=31; $i++)
{
printf('<option value="%d" %s>%d</option>', $i, $i == $day ? 'selected="selected"' : '', $i);
}
?>
</select>
<br>
<br>
<br>
<select name="month">
<option value="month" selected="selected">Month</option>
<?php
for($i=1; $i<=12; $i++)
{
echo "<option value=".$i.">".$i."</option>";
}
?>
</select>
<br>
<br>
<br>
<select name="years">
<option value="years" selected="selected">Years</option>
<?php
for($i=2000; $i<=2020; $i++)
{
echo "<option value=".$i.">".$i."</option>";
}
?>
</select>
<input type="submit" name="submit" value="Verify Date">

First, you'll need to add your <form action="action.php" method="post"></form> tags so the browser knows where to post the data to. In your "action.php" file, you can retrieve the values the user set the controls to when the form is submitted using the $_POST array:
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
EDIT: If you wish to use the GET method instead of POST, then simply replace $_POST with $_GET.

Try it
<p><font size="6"> <b>TP3</b></font></p>
<p>
</p>
<table align="center" width="800" border="1" cellspacing="2" cellpadding="2">
<tr>
<td><p><?php echo "Date : " . date("Y/m/d") . "<br>";?></p><br/>
<?php $date = new DateTime();
$day = $date->format('d');
$month = $date->format('m');
$year = $date->format('Y'); ?>
<select name="day">
<option value="day" selected="selected">Day</option>
<?php
$i=1;
for($i=1; $i<=31; $i++)
{
printf('<option value="%d" %s>%d</option>', $i, $i == $day ? 'selected="selected"' : '', $i);
}
?>
</select>
<br>
<br>
<br>
<select name="month">
<option value="month" selected="selected">Month</option>
<?php
$i=1;
for($i=1; $i<=12; $i++)
{
echo "<option value=".$i.">".$i."</option>";
}
?>
</select>
<br>
<br>
<br>
<select name="years">
<option value="years" selected="selected">Years</option>
<?php
$i=2000;
for($i=2000; $i<=2020; $i++)
{
echo "<option value=".$i.">".$i."</option>";
}
?>
</select>
<input type="submit" name="submit" value="Verify Date">

Firstly, you're missing <form></form> tags (this is very important).
Then a method (GET or POST), but we'll be using POST for this: method="post".
<form> defaults to GET if the method is omitted, a quick FYI.
Then there's the action (see further down below for an examle). The action determines if you wish to execute and show the data pulled in from your form inside the same file action=""
or using an external file action="handler.php".
Here:
<p><font size="6"> <b>TP3</b></font></p>
<p>
</p>
<table align="center" width="800" border="1" cellspacing="2" cellpadding="2">
<tr>
<td><p><?php echo "Date : " . date("Y/m/d") . "<br>";?></p><br/>
<?php $date = new DateTime();
$day = $date->format('d');
$month = $date->format('m');
$year = $date->format('Y'); ?>
<form action="" method="post">
<select name="day">
<option value="day" selected="selected">Day</option>
<?php
for($i=1; $i<=31; $i++)
{
printf('<option value="%d" %s>%d</option>', $i, $i == $day ? 'selected="selected"' : '', $i);
}
?>
</select>
<br>
<br>
<br>
<select name="month">
<option value="month" selected="selected">Month</option>
<?php
for($i=1; $i<=12; $i++)
{
echo "<option value=".$i.">".$i."</option>";
}
?>
</select>
<br>
<br>
<br>
<select name="years">
<option value="years" selected="selected">Years</option>
<?php
for($i=2000; $i<=2020; $i++)
{
echo "<option value=".$i.">".$i."</option>";
}
?>
</select>
<input type="submit" name="submit" value="Verify Date">
</form>
Plus, I don't know what type of action you wish to use, that will be up to you to decide.
So change action="" to the file handler you wish to use.
I.e.: action="handler.php" and do your magic from there.
Example of handler.php: and will produce for example Day: 14 Month: 10 Year: 2014
<?php
if(isset($_POST['submit'])){
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['years'];
echo "Day: " . $day . " ";
echo "Month: " . $month . " ";
echo "Year: " . $year;
}
?>
You can place the above inside its own file, or place it below:
// rest of code from your form/code
<input type="submit" name="submit" value="Verify Date">
</form>
<?php
if(isset($_POST['submit'])){
$day = $_POST['day'];
// rest of code
I believe this has answered your question.
Mark it as accepted to close the question properly:
The full article: https://meta.stackexchange.com/q/5234/

Related

Populate drop down form with months and year php

I am trying to create two drop downs with HTML and PHP. The first is an auto submit that sends a month to a session variable:
<form action="" method="post">
<select name="month" onchange="this.form.submit()">
<option value="">-- Select Month --</option>
<?php $month = date('n'); // current month
for ($x = 0; $x < 12; $x++) { ?>
<option value="<?php echo date('m', mktime(0,0,0,$month + $x,1)); ?>"
<?php echo date('m', mktime(0,0,0,$month + $x,1)) == $_SESSION['month'] ? "selected='selected'":""; ?> >
<?php echo date('F Y', mktime(0,0,0,$month + $x,1)); ?>
<?php } ?>
</select>
</form>
This works great. But I then need a second drop down with the day name and number:
<form action="" method="post">
<select name="day" onchange="this.form.submit()">
<option value="">-- Select Day --</option>
<?php for ($i = $current_day; $i < 31; $i++) {
$tmp_date = $_SESSION['year']."/".$_SESSION['month']."/".$i;
$weekday = date('D', strtotime($tmp_date)); { ?>
<option value="<?php echo $i; ?>" <?php echo $i == $_SESSION['day'] ? "selected='selected'":""; ?> >
<?php echo $weekday." ".$i; ?>
<?php } ?>
<?php } ?>
</option>
<?php } ?>
</select>
</form>
This uses a temp date with a session variable as '2014' which I set before. I need to remove the session year variable and get the first drop down to know which year the month selected is and then pass this to the temp date so that it populates the day name and number correctly for the next year (2015) if you choose January onwards. At the moment it only shows the day name and number from the current year (2014) in this case.
<?php
if(isset($_POST)) {
$date = explode('-', $_POST['month']);
$year = $date[0];
$month = $date[1];
echo "Year: ".$year." Month: ".$month;
}
?>
<form action="" method="post">
<select name="month" onchange="this.form.submit()">
<?php
for ($i = 0; $i <= 12; ++$i) {
$time = strtotime(sprintf('+%d months', $i));
$value = date('Y-m', $time);
$label = date('F Y', $time);
printf('<option value="%s">%s</option>', $value, $label);
}
?>
</select>
This gives me the year and month as separate values.
I had to check the print out of the first script, because it didn't make much sense...
<form action="" method="post">
<select name="month" onchange="this.form.submit()">
<option value="">-- Select Month --</option>
<option value="11"
>
November 2014 <option value="12"
>
December 2014 <option value="01"
>
January 2015 <option value="02"
>
February 2015 <option value="03"
>
March 2015 <option value="04"
>
April 2015 <option value="05"
>
May 2015 <option value="06"
>
June 2015 <option value="07"
>
July 2015 <option value="08"
>
August 2015 <option value="09"
>
September 2015 <option value="10"
>
October 2015 </select>
</form>
Might be I'm missing something, because it seemed to work, but it doesn't seem like you're closing the option tags. You are doing this:
<option value="11">November 2014
<option value="12">December 2014
Instead of this:
<option value="11">November 2014</option>
<option value="12">November 2014</option>
This doesn't seem to be the issue though, at least not in chrome, because when I checked the head data being sent, it was just fine:
month: 11
What happens when you send in the variable is that whatever page you send this form data with the method POST against will have to handle it further on. In PHP you do that with the global variable $_POST, in this case $_POST['month'].
if(!empty($_POST['month']))
{
echo $_POST['month'];
}
If you want to make it a session variable, the page you send the form data to will have to communicate with your browser to set this (through the reply HTTP header field). To do anything related to session in PHP you must first start a session using the session_start() before any HTML/data is sent against the browser, and the same goes for if you want to set a session variable using for example session_set_cookie_params. You also got setcookie, which also must be used before any data/HTML is sent to the browser and the variables can be accessed through $_COOKIE.
See if you can make some sense out of this, I've just used $_POST in this case, you can swap it with session or cookie and remember to send it before any data/html to the browser.
<?php
$selmonth = 0;
if(!empty($_POST['month']))
{
$selmonth = $_POST['month'];
}
$month = date('n'); // current month
echo '<form action="" method="post">
<select name="month" onchange="this.form.submit()">
<option value="">-- Select Month --</option>';
for($i=0; $i<12; $i++)
{
$monthtime = mktime(0,0,0,$month + $i,1);
$monthnum = date('m', $monthtime);
echo '
<option value="'.$monthnum.'"'.
($monthnum == $selmonth ? ' selected="selected"' : '').
'>'.date('F Y', $monthtime).'</option>';
}
echo '
</select>
</form>';
?>
<select required="" class="btn btn-warning btn-raised" onchange="loadMonthYear(this)">
<?php
$fdt = date('Y-m-1');
$tdt = date('Y-m-1', strtotime("-12 months"));
while (date('Ymd', strtotime($fdt)) >= date('Ymd', strtotime($tdt))) {
echo '<option value="'.date('M, Y', strtotime($fdt)).'"><a data-tag="' . date('M, Y', strtotime($fdt)) . '" href="javascript: void(0);">' . date('M, Y', strtotime($fdt)) . '</option>';
$fdt = date('Y-m-1', strtotime("-1 months", strtotime($fdt)));
}
?>
</select>

PHP Displaying current month in option select

How to make the current month selected by default in option select using php
Here is what i have tried so far.
$curmonth = date("F");
And to display the entire month
<select>
<?php
for($i = 1 ; $i <= 12; $i++)
{
$allmonth = date("F",mktime(0,0,0,$i,1,date("Y")))
?>
<option value="<?php
echo $i;
if($curmonth==$allmonth)
{
echo 'selected';
}
?>"
>
<?php
echo date("F",mktime(0,0,0,$i,1,date("Y")));
}
?>
</option>
And according to the above code, I am assigning the current month as $curmonth, and inside loop assigning the $allmonth for entire, month.
And inside the Value
<option value="<?php
echo $i;
if($curmonth==$allmonth)
{
echo 'selected';
}
?>"
>
<?php
echo date("F",mktime(0,0,0,$i,1,date("Y")));
}
?>
</option>
for checking if the current month equals all month and displaying the selected to make it select. But i am not getting result.. What i am getting is all the items are being displayed in the option select.
What i am missing ?
What you have missed is,
You are trying to display the selected inside the value
What you need to do is
<option value="<?php
echo $i;
?>"
<?php
if($allmonth==$curmonth)
{
echo ' selected';
}
?>
>
<?php
echo $allmonth;
}
?>
</option>
So, the result will be
<select >
<option value="1">
January<option value="2">
February<option value="3">
March<option value="4">
April<option value="5">
May<option value="6">
June<option value="7">
July<option value="8">
August<option value="9" selected>
September<option value="10">
October<option value="11">
November<option value="12">
December</option>
You're not correctly closing the <option> tags you are creating. Indenting you're code makes these issues more apparent:
<select>
<?php
for($i = 1 ; $i <= 12; $i++)
{
$allmonth = date("F",mktime(0,0,0,$i,1,date("Y")))
?>
<option value="<?php
echo $i;
if($curmonth==$allmonth)
{
echo 'selected';
}
?>"
>
<?php
echo date("F",mktime(0,0,0,$i,1,date("Y")));
//Close tag inside loop
?>
</option>
<?php
}
Hope you are wrong here
<option value="<?php
echo $i; ?>"
<?php
if($curmonth==$allmonth)
{
echo 'selected';
}
?>"
>
<?php
echo date("F",mktime(0,0,0,$i,1,date("Y")));
}
?>
</option>
You have missed closing quotes for the value
Take a look on this example:
$current = date('F');
for($i = 1 ; $i <= 12; $i++) {
$month = date("F",mktime(0,0,0,$i,1,date("Y")));
if( $current == $month )
echo $month . " - Selected \r\n";
else
echo $month . "\r\n";
}
IN HTML FORMAT:
echo "<select>";
$current = date('F');
for($i = 1 ; $i <= 12; $i++) {
$month = date("F",mktime(0,0,0,$i,1,date("Y")));
if( $current == $month )
echo "<option value='$month' selected='selected'>" $month . "</option>";
else
echo "<option value='$month'>" $month . "</option>";
}
echo "</select>";
DEMO
You have error with closing quotes in the value of options in the line
<option value="<?php
echo $i; if($curmonth==$allmonth)
{
echo 'selected';
}
?>"
^ // This is the quotes opened for value and is not properly closed
>
Here you have to close the quotes. As per your code it will display as:
<option value="9 selected" >
Also you are not closing <option> properly. Change your code to :
<select>
<?php
for($i = 1 ; $i <= 12; $i++)
{
$allmonth = date("F",mktime(0,0,0,$i,1,date("Y")))
?>
<option value="<?php echo $i;?>" <?php if($curmonth==$allmonth){echo 'selected';}?> >
^ // close quotes here
<?php
echo $allmonth;?>
</option>
}
</select>

Get Array Value

I have one form that have a select box inside while-loop. I try to get the data or value from that select box. Below is my form code.
<form role="form" method="post" action="test2.php" >
<?php
$endDate = '2014-01-28';
$startDate = '2014-01-27';
$daydiff = floor( ( strtotime( $endDate ) - strtotime( $startDate ) ) / 86400 );
$x=0;
while($x<=$daydiff)
{
?>
<select class="form-control" name="day_<?php echo $x; ?>">
<option value="monday">Monday</option>
<option value="tuesday">Tuesday</option>
<option value="wednesday">Wednesday</option>
<option value="thursday">Thursday</option>
</select>
<select class="form-control" name="time_<?php echo $x; ?>">
<option value="10am">10am</option>
<option value="11am">11am</option>
<option value="12pm">12pm</option>
<option value="1pm">1pm</option>
</select>
<?php
$x++;
}
?>
<input type="hidden" name="count" value="<?php echo $x ?>"/>
<button type="submit" name="submit" class="btn btn-primary btn-lg btn-block">Submit</button>
</form>
Below is my "test2.php".
<?php
for ($i = 0; $i < $_POST['count']; $i++){
$day_var = 'day_' . $i;
$days_list[] = $_POST[$day_var];
$time_var = 'time_' . $i;
$time_list[] = $_POST[$time_var];
echo ($_POST[$day_var]);
echo ($_POST[$time_var]);
}
?>
When I submit it will echo "monday10tuesday11am" how can I extract the value separately i.e. monday10 and tuesday11am?
You can replace your numbering scheme and variable variables with a simple array in HTML.
<select class="form-control" name="day[<?php echo $x; ?>]">
<select class="form-control" name="time[<?php echo $x; ?>]">
$days_list[] = $_POST[$day];
$time_list[] = $_POST[$time];
This would greatly simplify your form2.php. Otherwise, please try to explain what results you are expecting with the code you have.
just add some space to your echo.
echo ($_POST[$day_var]).' '.($_POST[$time_var]);

Multiple Form Dropdown Form, Validation, PHP

I have this whole code. Jumbled but what I'm trying to do is to have a drop down menu with selections from 1 -10. Then after selecting one, would spit out another form so that if there 3 were selected, would show three rows of fields (name, email). Validation included. What I was first "hard coded" on how many rows of fields to spit out but now what I wanted to do is to have a "selection" in dropdown menu so that the user has the ability to select.... Seem to work but doesn't process. Any PHP expert help? No db, no client-base, no smart alec. If you have time to help please do.
<!DOCTYPE html>
<html>
<head>
<title>PHP FORM </title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="container">
<?php
// Print some introductory text:
echo '<h2>Party Invitation Form</h2>
<p>Please enter list of people with first name, last name and email address to get an invitation by email.</p>';
if (isset($_POST['submit-invite'])) { //DROPDOWN MENU
$row = $_POST['invitee'];
// Check if the form has been submitted:
if (isset($_POST['submit'])) {
$problem = FALSE; // No problems so far.
// Check for each value...
for ($i = 1; $i < count($_POST['email']); $i++) {
if (empty($_POST['firstname'][$i])) {
$problem = TRUE;
echo '<input type="text" name="firstname[]" size="20" />';
}
if (empty($_POST['lastname'][$i])) {
$problem = TRUE;
}
if (empty($_POST['email'][$i]) || (substr_count($_POST['email'][$i], '#') != 1) ) {
$problem = TRUE;
}
}
if (!$problem) { // If there weren't any problems...
// Print a message:
echo '<p><b>Thank you for registering! We will send each one an invitation: <b> </b></p>';
for ($i = 0; $i < count($_POST['email']); $i++) {
$row = $i+1;
echo $row.": ".$_POST['firstname'][$i]." ".$_POST['lastname'][$i].", ".$_POST['email'][$i]." <br/>";
// Send the email:
$body = file_get_contents("Lab12_Obj1_email_template.txt");
$body = str_replace("#firstname#",$_POST['firstname'][$i],$body);
$body = str_replace("#lastname#",$_POST['lastname'][$i],$body);
$body = str_replace("#email#",$_POST['email'][$i],$body);
mail($_POST['email'][$i], 'Party Invitation', $body, 'From: jvicencio#johnvicencio.com');
}
// Clear the posted values:
$_POST = array();
} else { // Forgot a field.
echo '<p id="error">* Required field! Please try again. Thank you.</p>';
}
} // End of handle form IF.
//show form
?>
<form action="" method="post">
<table>
<tr style="font-weight:bold">
<td>First name:</td>
<td>Last name:</td>
<td>Email:</td>
</tr>
<?php for ($i = 1; $i <= $row; $i++) { ?>
<tr>
<td><?php if ($problem == TRUE) { echo '<p id="error">*'; } ?>
<? echo $i.': '; ?><input type="text" name="firstname[]" size="20" value="<?php if (isset($_POST['firstname'][$i])) { print htmlspecialchars($_POST['firstname'][$i]); } ?>" />
</td>
<td><?php if ($problem == TRUE) { echo '<p id="error">*'; } ?>
<input type="text" name="lastname[]" size="20" value="<?php if (isset($_POST['lastname'] [$i])) { print htmlspecialchars($_POST['lastname'][$i]); } ?>" />
</td>
<td><?php if ($problem == TRUE) { echo '<p id="error">*'; } ?><input type="text" name="email[]" size="20" value="<?php if (isset($_POST['email'][$i])) { print htmlspecialchars($_POST['email'][$i]); } ?>" />
</td>
</tr>
<?php } ?>
<tr><td><p><input type="submit" class="button" name="submit" value="Register!" /></td>
</tr>
</table>
</form>
<?php
}
else {
echo '
<form action="" method="post">
<select name="invitee">
<option value="">Select</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
<option value="7">Seven</option>
<option value="8">Eight</option>
<option value="9">Nine</option>
<option value="10">Ten</option>
</select>
<input type="submit" class="button" name="submit-invite" value="Invite">
</form>
';
}
?>
</div>
</body>
</html>
You have to move the second form submit code outside of first form submit. Try this
<!DOCTYPE html>
<html>
<head>
<title>PHP FORM </title>
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<div id="container">
<?php
// Print some introductory text:
echo '<h2>Party Invitation Form</h2>
<p>Please enter list of people with first name, last name and email address to get an invitation by email.</p>';
if (isset($_POST['submit-invite'])) { //DROPDOWN MENU
$row = $_POST['invitee'];
$problem = false; //always try to initialize variables, you may not run into unexpected warnings and problems.
//show form
?>
<form action="" method="post">
<table>
<tr style="font-weight:bold">
<td>First name:</td>
<td>Last name:</td>
<td>Email:</td>
</tr>
<?php for ($i = 1; $i <= $row; $i++) { ?>
<tr>
<td><?php if ($problem == TRUE) {
echo '<p id="error">*';
} ?>
<? echo $i . ': '; ?><input type="text" name="firstname[]" size="20"
value="<?php if (isset($_POST['firstname'][$i])) {
print htmlspecialchars($_POST['firstname'][$i]);
} ?>"/>
</td>
<td><?php if ($problem == TRUE) {
echo '<p id="error">*';
} ?>
<input type="text" name="lastname[]" size="20"
value="<?php if (isset($_POST['lastname'] [$i])) {
print htmlspecialchars($_POST['lastname'][$i]);
} ?>"/>
</td>
<td><?php if ($problem == TRUE) {
echo '<p id="error">*';
} ?><input type="text" name="email[]" size="20"
value="<?php if (isset($_POST['email'][$i])) {
print htmlspecialchars($_POST['email'][$i]);
} ?>"/>
</td>
</tr>
<?php } ?>
<tr>
<td><p><input type="submit" class="button" name="submit" value="Register!"/></td>
</tr>
</table>
</form>
<?php
} // moved second for submit to here
elseif (isset($_POST['submit'])) { // Check if the form has been submitted:
$problem = FALSE; // No problems so far.
// Check for each value...
for ($i = 1; $i < count($_POST['email']); $i++) {
if (empty($_POST['firstname'][$i])) {
$problem = TRUE;
echo '<input type="text" name="firstname[]" size="20" />';
}
if (empty($_POST['lastname'][$i])) {
$problem = TRUE;
}
if (empty($_POST['email'][$i]) || (substr_count($_POST['email'][$i], '#') != 1)) {
$problem = TRUE;
}
}
if (!$problem) { // If there weren't any problems...
// Print a message:
echo '<p><b>Thank you for registering! We will send each one an invitation: <b> </b></p>';
for ($i = 0; $i < count($_POST['email']); $i++) {
$row = $i + 1;
echo $row . ": " . $_POST['firstname'][$i] . " " . $_POST['lastname'][$i] . ", " . $_POST['email'][$i] . " <br/>";
// Send the email:
$body = file_get_contents("Lab12_Obj1_email_template.txt");
$body = str_replace("#firstname#", $_POST['firstname'][$i], $body);
$body = str_replace("#lastname#", $_POST['lastname'][$i], $body);
$body = str_replace("#email#", $_POST['email'][$i], $body);
mail($_POST['email'][$i], 'Party Invitation', $body, 'From: jvicencio#johnvicencio.com');
}
// Clear the posted values:
$_POST = array();
} else { // Forgot a field.
echo '<p id="error">* Required field! Please try again. Thank you.</p>';
}
} // End of handle form IF.
else {
echo '
<form action="" method="post">
<select name="invitee">
<option value="">Select</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
<option value="6">Six</option>
<option value="7">Seven</option>
<option value="8">Eight</option>
<option value="9">Nine</option>
<option value="10">Ten</option>
</select>
<input type="submit" class="button" name="submit-invite" value="Invite">
</form>
';
}
?>
</div>
</body>
</html>

Programmatically generating a drop-down menu

I have a drop down menu below:
$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>
";
Notice the drop down menus are in a php varaible in a form. My question is: "is there a much better and shorter method of displaying the drop down menu above?". Maybe by using some sort of loop to loop through each value and give each option the same value attribute?
I want to use getyear in order to fit in a simple if statement:
if ($getyear){
echo "year is chosen";
}else{
$errormsg = "You must enter in Student's current Academic Year to Register";
}
UPDATE:
<?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;
?>
The foreach loop is extremely beneficial when looping over arrays and performing operations on their values.
foreach control structure
<?php
// reference values for output and for validation later
$min_year = 1900; // using as an example
$max_year = 2012;
$years = range($min_year, $max_year); // returns array with numeric values of 1900 - 2012
// for HTML output
if (empty($_POST)) { // display form
$html = '';
foreach ($years as $year) {
$html .= "<option>$year</option>"; // if no value attribute, value will be whatever is inside option tag, in this case, $year
}
// output HTML
echo $html;
} else { // process form
$chosen_year = isset($_POST['year']) ? $_POST['year'] : "";
if (!in_array($chosen_year , $years) { // year is invalid
$errormsg = "You must enter in Student's current Academic Year to Register";
} else { // year is chosen
echo 'year is chosen';
}
}
This file will generate the select options automatically, and give you an easy place to do further processing.
function process_form(){
if(!isset($_POST['year']) || !is_numeric($_POST['year'])){
// Form invalid
return false;
}
$year = $_POST['year'];
// Perform actions - save to database, etc..?
// Form valid
return true;
}
$error = false;
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// Form submitted
$result = process_form();
if($result){
?>
<p>Valid year selected</p>
<?php
exit;
}
$error = true;
}
?>
<form action="" method="post">
<?php if($error){ ?>
<p class="error">You must select the student's current academic year to register</p>
<?php } ?>
<label for="select_year">Academic Year:</label>
<select name="year" id="select_year">
<option value=""></option>
<?php for($year = $start_year; $year <= $end_year; $year++){ ?>
<option value="<?php echo $year;?>"><?php echo $year;?></option>
<?php } ?>
</select>
<button type="submit">Register</button>
</form>

Categories