use of dropdown list PHP - php

i have two questions. this is my code (Iranian calender), the problem is when i want see results. all values of year and month and day showns as '$year' and 'month' and 'day'.
<?php
echo'<select dir="rtl" name="year">';
for($year=1388;$year<=1410;$year++)
{
echo '<option value="$year">$year</option>';
}
echo'</select>';
echo'<select dir="rtl" name="month">';
for($month=1;$month<=12;$month++)
{
echo '<option value="$month">$month</option>';
}
echo'</select>';
echo'<select dir="rtl" name="day">';
for($day=1;$day<=31;$day++)
{
echo '<option value="$day">$day</option>';
}
echo'</select>';
?>
second question:
and i need another thing. in Iranian calendar month 1 to 6 have 31 days and 7 to 12 have 30 days so i need a conditional expression when user choose month 1 to 6 show 31 days to choose and when user chooses month 7 to 121 show 30 days.

You use double quotes inside of single quotes so it will be rendered as string.
Make the changes accordingly:
From:
echo '<option value="$year">$year</option>';
To:
echo '<option value="'.$year.'">'.$year.'</option>';
echo '<option value="'.$month.'">'.$month.'</option>';
echo '<option value="'.$day.'">'.$day.'</option>';
EDIT (answer to your second question):
JSFIDDLE
First you need to give an id attribute to your select fields.
<select dir="rtl" name="month" id="month">
<select dir="rtl" name="day" id="day">
Then you need to add some JQuery code that checks if month is greater than 6 so it will remove the last option (only if days are 31). If month is equal of 6 or less then will add a new option (only if days are 30).
$('#month').on('change', function() {
var monthValue = $(this).val();
var dayOptions = $('#day option').size();
if (monthValue > 6 && monthValue <=12) {
if (dayOptions == 31) {
$("#day option:last").remove();
}
} else if (monthValue >= 1 && monthValue <= 6) {
if (dayOptions == 30) {
$('#day').append($('<option>', {
value: 31,
text: 31
}));
}
}
});

you need to use " or use concatenation with . with '
so this should be:
echo '<option value="$day">$day</option>';
this:
echo '<option value="' . $day . '">' . $day . '</option>';
or this:
echo "<option value=\"$day\">$day</option>";

Related

PHP - Setting default year in selection box

I am new to PHP. I have a selection box with a range of years starting at current year - 5 (2014) through the year 2050. My selection box contains the correct years but I need it to default to the current year. Right now, it defaults to 2014. I've been working on this for hours. I thought the $current_year variable was needed in the loop in some way - in order to set the default - but that doesn't work. After researching and seeing various examples, I'm now thinking I need to build an if statement within the loop but I really don't know.
<form id="calendarForm" name="calendarForm" method="post" action="">
<label for="select_year">Select the year: </label>
<select id="select_year" name="select_year">
<?php
$date = new DateTime();
// Sets the current year
$current_year = $date->format('Y');
// Year to start available options.
$earliest_year = ($current_year - 5);
$year = $earliest_year;
for ($year = $earliest_year; $year <= LATEST_YEAR; $year++) {
echo "<option value='$year'>$year</option>";
}
?>
</select>
Modify your for loop as follows:
for ($year = $earliest_year; $year <= LATEST_YEAR; $year++) {
if($year==$current_year)
{
echo "<option value='$year' selected>$year</option>";
}
else{
echo "<option value='$year'>$year</option>";
}
}
Try the following. You need to adjust your php tags but neat.
<option value='$year' <?php if($year == date("Y")) {echo "selected";}?> >$year</option>";
It will check against the current year and will be the selected option if matched.

How do I get the year value of the selected option with the present year in PHP?

I have a combobox of year options with 2 year interval. If the user selects the one with the present year which is 2014-2016 (because 2016 is the present year). I want to get or know that the user's option is the one with the current year. Don't mind about the rest option, but just the one with the present year because I'm gonna use it in another condition. Help please.
<select name="year">
<option>Year:</option>
<?php
for($i=date('Y'); $i>1999; $i=$i-2) {
$selected = '';
$year2 = $i-2;
if ($year == $i) $selected = ' selected="selected"';
echo ('<option value="'.$year2. " - " . $i .'" '.$selected.'> '.$year2.' - '.$i.'</option>'."\n");
}
?>
</select>

Leap year friendly year/month/day select option tags with PHP embedded

I'm trying to write codes with PHP to enable leap year friendly select option tags. For example, you pick a year, then it checks if it is a leap year or not, then it shows a pull down menu (select option tags) of days preceded by another select option tags of 12 months. PHP codes are embedded in HTML. Here is my failed attempt below (I'm new to PHP):
<form method="post">
<select name="year">
<option value="" selected>Pick a year</option><!--Default-->
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
</select>
<select name="month">
<option value="" selected>Pick a month</option><!--Default-->
<!--Show all 12 months-->
<?php for( $i = 1; $i <= 12; $i++ ): ?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php endfor; ?>
</select>
<select name="day">
<option value="" selected>Pick a day</option><!--Default-->
<!--Show dates depending on the conditions below:-->
<?php
if ( $month == 1 || 3 || 5 || 7 || 8 || 10 || 12 )
{
//Show dates until 31
for ( $i = 1; $i <= 31; $i++ )
{
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
}
elseif ( $month == 2 )
{
//Leap year
if ( $year != "" && $year % 4 == 0 && $year % 100 == 0 && $year % 400 == 0 )
{
//Show dates until 29
for ( $i = 1; $i <= 29; $i++ )
{
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
}
//Regular year (Non-leap year)
else
{
//Show dates until 28
for ( $i = 1; $i <= 28; $i++ )
{
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
}
}
elseif ( $month == 4 || 6 || 9 || 11 )
{
//Show dates until 30
for ( $i = 1; $i <= 30; $i++ )
{
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
}
?>
</select>
<input type="submit" value="submit">
</form>
Notes:
I understand that the above is the incomplete code and it doesn't work. Besides, I don't know how to define $year or $month or $day from the select tags. Should I do it like this? If so, where should I put it?
<?php
if( $_SERVER["REQUEST_METHOD"] == "POST" )
{
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
//The rest of the php code?
}
?>
Preferably, I do not want to show years by using for loops as in months and days. I would like to do it manually this time (sorry, but if you suggest I should use the for loop, I appreciate your advise).
I wrote $year =! "" in the leap year February if block because I want to evade the empty default values from being counted.
I warmly welcome your suggestions and corrections, please help me out :)
Thanks in advance!
As far as I know about leap year:
/**
* In the Gregorian calendar 3 criteria must be taken into account to identify leap years:
* 1. The year is evenly divisible by 4;
* 2. If the year can be evenly divided by 100, it is NOT a leap year, unless;
* 3. The year is also evenly divisible by 400. Then it is a leap year.
*
* #param $year integer
* #return bool
*/
private static function isLeapYear($year)
{
// the rule was applied after 1582
if ($year > 1582) {
if (($year % 400 == 0 && $year % 100 != 0) || ($year % 4 == 0))
{
//"It is a leap year"
return true;
}
else
{
return false;
//"It is not a leap year"
}
}
return false;
}
This won't work:
( $month == 1 || 3 || 5 || 7 || 8 || 10 || 12 )
This will only check that $month == 1, then the other conditions will be evaluated to true because the integers are evaluated to true (and PHP can't compare a variable to booleans with this code).
It looks like you're trying to get the number of days per month. This can be done easily with DateTime::Format() that use the date() format:
t returns the Number of days in the given month:
$dt = new Datetime('2016-02-15');
print $dt->format('t');
// display "29"
Example.
L returns the 1 if a year is leap, 0 otherwise:
$dt = new Datetime('2016-02-15');
print $dt->format('L');
// display "1"
$dt = new Datetime('2015-02-15');
print $dt->format('L');
// display "0"
Example.
You should probably don't care about the inputs and display all the years, the 12 months and 31 days per month and check the date with checkdate() once the data have been submitted.

PHP Appending year the select menu

I have this custom function in place, It will get the current year from the date function in php. When next year will come I want to append next year with previous year.
Example:
Current Year is "2013"
Next year will be "2014"
When year will come, It should dynamically add 2014 to drop-down list.
<select>
<option>2014</option>
<option>2013</option>
</select>
function ec_year(){
$year = date("Y");
}
Anyone any help please.
Use this :
$start_year = '2013';
$current_year = date("Y");
echo '<select>';
for ($i=$start_year; $i <= $current_year; $i++) {
echo '<option>' . $i .'</option>';
}
echo '</select>';
Try this give the end year as you like ...it will automatically work on present year
<select>
<?php for($i=date(Y);$i>=endyear);$i--){
<option><?php echo $i;?></option>
<?php }?></select>
Try this:
<select>
<option><?php print(Date("Y") + 1); ?></option>
<option><?php print(Date("Y")); ?></option>
</select>
Try:
echo date('Y')+1; #will give current year + 1

Making a calender in PHP but can't get it into a grid

So I am making a calender form for a client to choose a course to book... this then uploads to a link table between the course and the customer but I cant for the life of me get the calender into a calender like grid properly... my code is simple and sweet but i need to do this non object orientated (i have small java experience but nothing else)....
I have ben staring at this all day but to no avail!
(I am learning so im not going down the routes of protecting it etc... this is for self learning so just needs to work and help me understand where I am going wrong)
The code:
<?
if(#$_POST['month'])
{
$_SESSION['month'] = trim($_POST['month']);
}
elseif(!isset($_SESSION['month']))
{
$_SESSION['month'] = '3';
}
if(#$_POST['year'])
{
$_SESSION['year'] = trim($_POST['year']);
}
elseif(!isset($_SESSION['year']))
{
$_SESSION['year'] = '2012';
}
?>
<form name="sort" action="calender.php" method="post">
<select name="month">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select name="year">
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
<option value="2022">2022</option>
<option value="2023">2023</option>
</select>
<input type="submit" value=" - !Go! - " />
</form><br />
<?php
$month = $_SESSION['month'];
$year = $_SESSION['year'];
$day = 1;
$nummonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
echo "<form name='choosedate' action='datechosen' method='get'>";
for($day = 1; $day <= $nummonth; $day++)
{
echo $day."/".$month."/".$year."<input type='radio' name='coursedate value='".$day."-".$month."-".$year."' /><br />";
}
echo "<input type='submit' value=' - Submit - ' /></form>";
?>
Thank you for any help you can give... any advice or even just a point in the right direction is much much much appreciated!
Here's a function I threw together that should work with your current code. To use the function, simply call it by this:
# $month, $year must be numeric. ie. Aug = 8
# The 3rd parameter is optional. It will display the calendar month starting
# on either Monday or Sunday, depending on your preference. Default is 'sun',
# but anything other than 'sun' will cause the displayed week to start on Monday.
printCalendarMonth($month, $year, 'mon');
Then you need to include the code below. I've commented in it to help.
function printCalendarMonth($month, $year, $firstDay = 'sun')
{
# Get the number of days in the month
$totalDays = cal_days_in_month(CAL_GREGORIAN, $month, $year);
# Get the day-of-the-week the 1st starts on
$date = getDayOfTheWeek($month,$year, $firstDay);
# print out the table headers
printTableHeader($date, $firstDay);
# print table body
printTableBody($totalDays, $date['startDay']);
# print out the table headers
printTableFooter();
}
function printTableHeader($date, $firstDay)
{
# The standard "Sunday First" calendar of days
$days = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
# change to the "Monday First" calendar
if($firstDay == 'mon'){
# the days of the week
$days = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');
}
# print the header HTML for the calendar table
echo '<h1>' . $date['month'] . ', ' . $date['year'] . '</h1>' . "\n";
echo '<table>' . "\n";
echo "\t" . '<thead>' . "\n";
echo "\t\t" . '<tr>' . "\n";
# loop through the days and print them out
foreach($days as $day){
echo "\t\t\t" . '<th>' . $day . '</th>' . "\n";
}
# close table header HTML
echo "\t\t" . '</tr>' . "\n";
echo "\t" . '</thead>' . "\n";
echo "\t" . '<tbody>' . "\n";
}
function printTableBody($totalDays, $startDay)
{
# value to represent the day the last day of the month falls on
$endDay = 6;
# value to represent the current day of the week
$currDay = 1;
# Loop through all the days of the month
for($todayDate=1; $todayDate <= $totalDays; $todayDate++){
# start a new row every 7 days
if($currDay % 7 == 1) { echo "\t\t" . '<tr>' . "\n"; }
# increment the current day (do this before the closing table row)
$currDay++;
# loop through the number of starting days to represent the days of the previous month
$currDay = printPrevMonthDays($startDay, $currDay);
# print out the table cell for this day. Start a new row for every 7 days
echo "\t\t\t" . '<td>'.$todayDate.'</td>' . "\n";
# close the table row every 7 days
if($currDay % 7 == 1) { echo "\t\t" . '</tr>' . "\n"; }
}
}
function printTableFooter($firstDay)
{
echo "\t" . '</tbody>' . "\n";
echo '</table>' . "\n";
}
function getDayOfTheWeek($month, $year, $firstDay = 'sun')
{
$date = array();
# save out the date values
$time = mktime(0, 0, 0, $month, 1, $year);
$date['dotw'] = strtolower( date("D", $time) );
$date['month'] = strtolower( date("F", $time) );
$date['year'] = strtolower( date("Y", $time) );
switch($date['dotw']){
default:
case 'sun': $date['startDay'] = 0; break;
case 'mon': $date['startDay'] = 1; break;
case 'tue': $date['startDay'] = 2; break;
case 'wed': $date['startDay'] = 3; break;
case 'thu': $date['startDay'] = 4; break;
case 'fri': $date['startDay'] = 5; break;
case 'sat': $date['startDay'] = 6; break;
}
# subtract one if we want to display Monday as the first day of the week
if($firstDay == 'mon')
$date['startDay'] = $date['startDay'] - 1;
# return date array object
return $date;
}
# passing startDay by reference
function printPrevMonthDays(&$startDay, $currDay)
{
while($startDay != 0){
echo "\t\t\t" . '<td>[blank]</td>' . "\n";
# increment the current day
$currDay++;
# decrement the startDay
$startDay--;
}
# return zero to
return $currDay;
}
The main concept is as DaveyBoy states, it's just a X-by-X array. The only real trick is that days don't always start on the first day of the week, so you need to print out some "blank" days of the previous month.
You could easily do this by creating a 7-by-X 2D array and just loop through that, but it will be the same concepts where you need to fill in the blank spaces.
Of course, there's some hard coded values in there, which can be improved upon but for the sake of this tutorial, here it is.
Hope it helps!
Cheers!
I've done this myself but it took quite a bit of doing. Nowadays, I use jQuery-ui.
There is a date picker built into it and it's pretty configurable. It can do individual dates or ranges. I've used it before and it was pretty simple to get going (even with my limited javaScript experience)
http://jqueryui.com/demos/datepicker/
I think that this is the code I describe in one of my comments below. Sorry if it's convoluted - it's from my early days as a PHP coder.
<?php
/**
* Calendar functions
*/
function ConvDate(&$D)
{
$TempDate=substr($D,8,2)."/".substr($D,5,2)."/".substr($D,0,4);
$D=$TempDate;
}
/**
* Function to display a calendar of a month
*/
function DispCalendar($Month=NULL,$Year=NULL, $Link=NULL, $VarName=NULL,$highlight=NULL)
{
$DIM=array('01'=>31,'02'=>28,'03'=>31,'04'=>30,'05'=>31,'06'=>30,'07'=>31,'08'=>31,'09'=>30,'10'=>31,'11'=>30,'12'=>31);
/**
* Set default values for Month and Year if none supplied
*/
if (empty($Month))
{
$Month=date("m");
}
if (empty($Year))
{
$Year=date("Y");
}
/**
* Add a leading zero to the month number if required
*/
$Month=str_pad($Month,2,"0",STR_PAD_LEFT);
/**
* Check for a leap year. The rule is that the year is divisible by 4 or 400 (eg 2000). Year values with an odd number of centuries (eg 1900)
* are NOT leap years. Easiest way to deal with this is all years where there is a remainder when dividing by 100 and none when
* dividing by 4 or when there is no remainder when dividing by 400
* Use the "Exact equivalence" operator (===) as 0 is used as a value for "false"
*/
if ((((($Year % 4)===0) && (($Year % 100)!==0)) || ($Year % 400)===0) && ($Month==2))
{
$DaysInMonth=29;
} else
{
$DaysInMonth=$DIM[$Month];
}
/**
* If a link has been passed and no variable name or vice versa, clear them as it's pointless having one without the other
*/
if ((isset($Link) && !isset($VarName)) || (!isset($Link) && isset($VarName)))
{
unset ($Link);
unset ($VarName);
}
/**
* First day of the selected month
*/
$FOMTS=mktime(0,0,0,$Month,1,$Year);
/**
* Today's date
*/
$todayDay=date("d");
$todayMonth=date("m");
$todayYear=date("Y");
/**
* Which day of the week does the first fall on. Sunday=0
*/
$FirstFallsOn=date("w",$FOMTS);
/**
* Full month name
*/
$LongMonth=date("F",$FOMTS);
$LongYear=$Year;
/**
* Start a table
*/
echo "<table width=\"100%\" class=\"cal\">\n";
/**
* Display the month and the year
*/
echo "\t<tr>\n";
echo "\t\t<th colspan=7>$LongMonth - $LongYear</th>\n";
echo "\t</tr>\n";
/**
* Display the days of the week
*/ echo "\t<tr>\n";
foreach (array("Sun","Mon","Tue","Wed","Thu","Fri","Sat") as $day)
{
echo "\t\t<td width=\"14.28%\">$day</td>\n";
}
echo "\t</tr>\n";
/**
* Pad out the table cells until the correct day of the week has been reached for the first of the month. Keep
* track of the number of cells
*/
echo "\t<tr>\n";
for ($dayCounter=0; $dayCounter<$FirstFallsOn; $dayCounter++)
{
echo "\t\t<td></td>\n";
}
/**
* Start a counter to keep track of the number of days displayed
*/
$dayOfMonth=1;
/**
* Display the days of the month
*/
for ($dayOfMonth=1; $dayOfMonth<=$DaysInMonth; $dayOfMonth++)
{
/**
* If the date being displayed is today's date, highlight it in a colour
*/
$class=((($dayOfMonth==$todayDay) && ($Year==$todayYear) && ($Month==$todayMonth)) ? " class=\"today\"" : ($highlight==($dayOfMonth.$Month.$Year) ? " class=\"calChosen\"" : NULL));
echo "\t\t<td$class>";
if (isset($Link))
{
$FL="$Link?$VarName=";
$FL.=str_pad($dayOfMonth,2,"0",STR_PAD_LEFT).$Month.$Year;
echo "$dayOfMonth";
} else
{
echo $dayOfMonth;
}
echo "</td>\n";
$dayCounter++;
if (($dayCounter % 7)===0)
{
echo "\t</tr>\n\t<tr>\n";
}
}
for (;($dayCounter%7)!==0; $dayCounter++)
{
echo "\t\t<td></td>\n";
}
echo "\t</tr>\n";
echo "</table>\n";
}
?>

Categories