Tải bản đầy đủ - 0 (trang)
Chapter 22. Creating a Simple Calendar

Chapter 22. Creating a Simple Calendar

Tải bản đầy đủ - 0trang

BuildingaSimpleDisplayCalendar

You'llusethedateandtimefunctionsyoulearnedinChapter8,

"WorkingwithStrings,Dates,andTime,"tobuildacalendar

thatwilldisplaythedatesforanymonthbetween1980and

2010.Theuserwillbeabletoselectbothmonthandyearwith

pull-downmenus,andthedatesfortheselectedmonthwillbe

organizedaccordingtothedaysoftheweek.Wewillbeworking

withtwovariablesoneformonthandoneforyearwhichtheuser

willsupply.Thesepiecesofinformationwillbeusedtobuilda

timestampbasedonthefirstdayofthemonthdefined.Ifthe

userinputisinvalidorabsent,thedefaultwillbethefirstdayof

thecurrentmonth.



CheckingUserInput

Whentheuseropensthecalendarapplicationforthefirsttime,

itwillbewithoutsubmittinganyinformation.Therefore,we

mustensurethatthescriptcanhandlethefactthatthe

variablesformonthandyearmaynotbedefined.Wecoulduse

theisset()functionforthis,whichreturnsfalseifthe

variablepassedtoithasnotbeendefined.However,let'suse

checkdate()instead,whichnotonlywillseeifthevariable

exists,butwillalsodosomethingmeaningfulwithit,namely,

validatethatitisadate.Listing22.1showsthefragmentof

codethatchecksformonthandyearvariablescomingfroma

form,andbuildsatimestampbasedonthem.



Listing22.1CheckingUserInputfortheCalendar

Script



1:
2:if(!checkdate($_POST['month'],1,$_POST['year'])){

3:$nowArray=getdate();

4:$month=$nowArray['mon'];

5:$year=$nowArray['year'];

6:}else{

7:$month=$_POST['month'];

8:$year=$_POST['year'];

9:}

10:$start=mktime(12,0,0,$month,1,$year);

11:$firstDayArray=getdate($start);

12:?>

Listing22.1isafragmentofalargerscript,soitdoesnot

produceanyoutputitself.Intheifstatementonline2,weuse

checkdate()totestwhetherthemonthandyearhavebeen

providedbyaform.Iftheyhavenotbeendefined,

checkdate()returnsfalsebecausethescriptcannotmakea

validdatefromundefinedmonthandyeararguments.This

approachhastheaddedbonusofensuringthatthedata

submittedbytheuserconstitutesavaliddate.

Ifthedateisnotvalid,weusegetdate()online3tocreatean

associativearraybasedonthecurrenttime.Wethensetvalues

for$monthand$yearourselves,usingthearray'smonandyear



elements(lines4and5).Ifthevariableshavebeensetfrom

theform,weputthedatainto$monthand$yearvariablesso

asnottotouchthevaluesintheoriginal$_POSTsuperglobal.

Nowthatwearesurethatwehavevaliddatain$monthand

$year,wecanusemktime()tocreateatimestampforthefirst

dayofthemonth(line10).Wewillneedinformationaboutthis

timestamplateron,soonline11,wecreateavariablecalled

$firstDayArraythatwillstoreanassociativearrayreturnedby

getdate()andbasedonthistimestamp.



BuildingtheHTMLForm

Weneedtocreateaninterfacebywhichuserscanasktosee

dataforamonthandyear.Forthis,wewilluseSELECT

elements.Althoughwecouldhard-codetheseinHTML,wemust

alsoensurethatthepull-downsdefaulttothecurrentlychosen

month,sowewilldynamicallycreatethesepull-downs,adding

aSELECTattributetotheOPTIONelementwhereappropriate.

TheformisgeneratedinListing22.2.



Listing22.2BuildingtheHTMLFormforthe

CalendarScript



1:
2:if(!checkdate($_POST['month'],1,$_POST['year'])){

3:$nowArray=getdate();

4:$month=$nowArray['mon'];

5:$year=$nowArray['year'];



6:}else{

7:$month=$_POST['month'];

8:$year=$_POST['year'];

9:}

10:$start=mktime(12,0,0,$month,1,$year);

11:$firstDayArray=getdate($start);

12:?>

13:

14:

15:<?phpecho"Calendar:".$firstDayArray['month']."<br /><br />16:".$firstDayArray['year']?>

17:

18:



19:
20:

21:


22:$months=Array("January","February","March","April","M



23:"June","July","August","September","October","November



24:for($x=1;$x<=count($months);$x++){

25:echo"
26:if($x==$month){

27:echo"SELECTED";

28:}

29:echo">".$months[$x-1]."";

30:}

31:?>

32:

33:

34:
35:for($x=1980;$x<=2010;$x++){

36:echo"
37:if($x==$year){

38:echo"SELECTED";

39:}

40:echo">$x";

41:}

42:?>



43:

44:

45:

46:

47:

Havingcreatedthe$starttimestampandthe$firstDayArray

datearray(lines211),let'swritetheHTMLforthepage.Notice

thatweuse$firstDayArraytoaddthemonthandyeartothe

TITLEelementonlines15and16.

Line19isthebeginningofourform.TocreatetheSELECT

elementforthemonthpull-down,wedropbackintoPHPmode

online21towritetheindividualOPTIONtags.First,wecreate

anarraycalled$monthsinlines22and23thatcontainsthe12

monthnames.Wethenloopthroughthisarray,creatingan

OPTIONtagforeachname(lines2430).Thiswouldprobablybe

anovercomplicatedwayofwritingasimpleSELECTelement

wereitnotforthefactthatwearetesting$x(thecounter

variableintheforstatement)againstthe$monthvariableon

line26.If$xand$monthareequivalent,weaddthestring

SELECTEDtotheOPTIONtag,ensuringthatthecorrectmonth

willbeselectedautomaticallywhenthepageloads.Weusea

similartechniquetowritetheyearpull-downonlines3541.

Finally,backinHTMLmode,wecreateasubmitbuttononline

44.

Wenowhaveaformthatcansendthemonthandyear

parameterstoitself,andwilldefaulteithertothecurrentmonth

andyear,orthemonthandyearpreviouslychosen.Ifyousave

thislistingaslisting22.2.php,placeitinyourWebserver



documentroot,andaccessitwithyourWebbrowser,you

shouldseesomethinglikeFigure22.1(yourmonthandyear

maydiffer).



Figure22.1.Thecalendarform.



CreatingtheCalendarTable

Wenowneedtocreateatableandpopulateitwithdatesfor

thechosenmonth.WedothisinListing22.3,whichrepresents

thecompletecalendarscript.



Listing22.3TheCompleteCalendarScript



1:


2:define("ADAY",(60*60*24));

3:if(!checkdate($_POST['month'],1,$_POST['year'])){

4:$nowArray=getdate();

5:$month=$nowArray['mon'];

6:$year=$nowArray['year'];

7:}else{

8:$month=$_POST['month'];

9:$year=$_POST['year'];

10:}

11:$start=mktime(12,0,0,$month,1,$year);

12:$firstDayArray=getdate($start);

13:?>

14:

15:

16:<?phpecho"Calendar:".$firstDayArray['month']."<br /><br />17:".$firstDayArray['year']?>

18:

19:



20:


21:

22:


23:$months=Array("January","February","March","April","M



24:"June","July","August","September","October","November

25:for($x=1;$x<=count($months);$x++){

26:echo"
27:if($x==$month){

28:echo"SELECTED";

29:}

30:echo">".$months[$x-1]."";

31:}

32:?>

33:

34:

35:
36:for($x=1980;$x<=2010;$x++){

37:echo"
38:if($x==$year){



39:echo"SELECTED";

40:}

41:echo">$x";

42:}

43:?>

44:

45:

46:

47:


48:


49:$days=Array("Sun","Mon","Tue","Wed","Thu","Fri","Sa

50:echo"\n";

51:foreach($daysas$day){



52:echo"$day

53:}

54:for($count=0;$count<(6*7);$count++){

55:$dayArray=getdate($start);

56:if(($count%7)==0){

57:if($dayArray['mon']!=$month){



58:break;

59:}else{

60:echo"\n";

61:}

62:}



63:if($count<$firstDayArray['wday']||$dayArray['mon']

64:echo" \n";

65:}else{



66:echo"".$dayArray['mday']."  \n

67:$start+=ADAY;

68:}

69:}

70:echo"";

71:?>

72:

73:

Becausethetablewillbeindexedbydaysoftheweek,weloop

throughanarrayofdaynamesinlines5153,printingeachto

itsowncellonline52.Alltherealmagicofthescripthappens



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 22. Creating a Simple Calendar

Tải bản đầy đủ ngay(0 tr)

×