Tải bản đầy đủ - 0 (trang)
3 Case Study: Using Sessions in Validation

3 Case Study: Using Sessions in Validation

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

validation

Example8-9displaysalltheerrorsinastand-alonepage

withnoconnectiontotheformpage,sotheusercannot

easilyseetherelationbetweenerrorsandtheoriginalinput

fields.

TheerrorpagegeneratedbyExample8-9isn'tsafefrom

thereloadproblemdescribedinChapter8.

Inthissectionwedevelopscriptsthatmakeuseofsession

variablestosolvetheseproblems.Ratherthandisplayingthe

errormessagesonapagegeneratedbythevalidationscript,

weshowyouhowtodisplaytheerrorsinredabovethe

appropriateinputfieldsonthedataentryform,asshownin

Figure10-3(theredtextappearsasalightgrayinthefigure).



Figure10-3.Thephonebookentryformshowing

errormessages



Figure10-4showshowtheimprovedformandthevalidate

scriptsinteractwithsessionmanagementtocommunicate

errorsandsubmittedfields.



Figure10-4.Phonebookentryformandvalidation



Becausethevalidationscriptprocessesthefieldscollectedin

thephonebookformandgeneratesanyassociatederrors,we

lookatthechangesrequiredforthatscriptfirst.



10.3.2TheValidationScript

Webegintheimprovementstothevalidationscriptwiththe

changesrequiredtosupportanerrormessagesessionvariable

andthendiscusshowtorecordthevaluestopassbacktothe

phonebookentryformgenerationcode.Wethenshowyouthe

completestructureofthemodifiedvalidationscript.



10.3.2.1Improvingerrormessages

Thevalidationscriptcheckseachvariablesubmittedfromthe

phonebookformtomakesuredatahasbeenentered.The

scriptshowninExample8-9buildsupatemplatebyadding

blocksaserrorsarefound.Inthemodifiedscriptweuseinthis

casestudy,anassociativearrayisregisteredinsteadtohold

errormessagesassociatedwitheachfield,providinggreater

flexibilitywhendisplayingtheerrormessages.

First,weneedtoinitializethesessionwithacallto

session_start()andsetup$errorstoholdanarrayoferrors:

//Initializeasession

session_start();



//Set-upanempty$errorsarraytoholderrors

$errors=array();



Thescriptthencheckseachvariableandaddsanerrormessage

totheassociativearray$errorsifanerrorisencountered.The

errormessagearrayisindexedbythenameofthefieldbeing

checked.Forexample,thevalidationofthesurnameiscoded

as:

//ValidatetheSurname

if(empty($surname))

$errors["surname"]="Thesurnamefieldcannotbeblank.";



Onceallthefieldshavebeenvalidated,thesizeofthe$errors

arrayistestedtodetermineifanyerrorswereencountered.If

thesizeofthearrayiszero,wecreateorupdatetherowas

before,otherwisewecarryoutseveralstepsasshowninthe

followingfragment:

//Nowthescripthasfinishedthevalidation,checkif

//therewereanyerrors

if(count($errors))

{



//Setupa$lastformVarsarraytostorethepreviously-enter

$lastformVars=array();

$lastFormVars["surname"]=$surname;

$lastFormVars["firstname"]=$firstname;

$lastFormVars["phone"]=$phone;



//Savethearrayasasessionvariable

$_SESSION["lastFormVars"]=$lastFormVars;



//Storethe$errorsarrayasasessionvariable

$_SESSION["errors"]=$errors;



//Relocatetothephonebookform

header("Location:example.10-5.php");

exit;

}



ThesetupanduseofthelastFormVarsarrayisdiscussedin

thenextsection.Theremainderofthefragmentsavesthe

$errorsarrayasasessionvariableandrelocatestothe

phonebookentryformscript.

InExample8-9,thescriptitselfdisplaysanyerrors,and

becausetherequestcontainsvariablesinaPOSTmethod

request,theerrorpagesuffersfromthereloadproblem

discussedinChapter8.Thescripthastodisplaytheerrors

immediately,inisolation,becausewithoutsessionsthereisno

convenientwaytosavetheerrorsandretrievethemagain

whendisplayingtheform.Inthevalidationscriptdeveloped

here,werelocatetothephonebookentryform(shownlaterin

Example10-5)andletitdisplaytheerrorsheldinthesession

variable$_SESSION["errors"].



10.3.2.2Savinglast-enteredvaluesasasession

variable

Wenowshowyouhowtopassthefielddatafromthevalidation

scriptbacktothephonebookentryform,sotheuserdoesnot

havetore-keydataafteranerroroccurs.Thefieldsarepassed

backthesessionarrayvariablelastFormVars.



Thefollowingcodefragmentsaveseachvalueenteredintothe

formintoa$lastFormVarsarray,indexedbythenameofthe

variable.The$lastFormVarsarrayisthensavedasthesession

variable$_SESSION["lastFormVars"].



//Setupa$lastformVarsarraytostorethepreviously-entered

$lastformVars=array();

$lastFormVars["surname"]=$surname;

$lastFormVars["firstname"]=$firstname;

$lastFormVars["phone"]=$phone;



//Savethearrayasasessionvariable

$_SESSION["lastFormVars"]=$lastFormVars;



Whenthemodifiedformisrun,themostrecentvaluesentered

fromthesessionvariable$_SESSION["lastFormVars"]are

shown.

Thefinalchangeneededistodestroythesessionwhenthe

scriptsuccessfullysavesarowinthephonebooktable:

//Destroythesession

session_destroy();



However,yourapplicationmaymakeuseofthesessionfor



otherpurposesandyoumaynotwanttodestroythesessionat

thispoint.Ifthisisthecasethenyoushouldunsetthevariables

usedinthesescripts.

//CleanupthelastFormVarsfromthesessionstore

unset($_SESSION["lastFormVars"]);



10.3.2.3Thefinalvalidationscript

Example10-4showsthefinalvalidationscriptderivedfrom

Example8-9.



Example10-4.Thecompletevalidationscript

derivedfromExample8-9


require'db.inc';



if(!($connection=@mysql_pconnect("localhost","fred","shhh

die("Couldnotconnecttodatabase");



$firstname=mysqlclean($_POST,"firstname",50,$connection);

$surname=mysqlclean($_POST,"surname",50,$connection);



$phone=mysqlclean($_POST,"phone",20,$connection);



//Initializeasession

session_start();



//Set-upanempty$errorsarraytoholderrors

$errors=array();



//ValidatetheFirstname

if(empty($firstname))



$errors["firstname"]="Thefirstnamefieldcannotbeblank."



//ValidatetheSurname

if(empty($surname))

$errors["surname"]="Thesurnamefieldcannotbeblank.";



//ValidatethePhonenumber.Itmusthavethecorrectformat

$validPhoneExpr="^([0-9]{2,3}[]?)?[0-9]{4}[]?[0-9]{4}$";



if(empty($phone)||!ereg($validPhoneExpr,$phone))



$errors["phone"]="Thephonenumbermustbe8digitsinleng



withanoptional2or3digitareacode"



//Nowthescripthasfinishedthevalidation,checkif

//therewereanyerrors

if(count($errors))

{

//Setupa$lastformVarsarraytostore

//thepreviously-entereddata

$lastformVars=array();

$lastFormVars["surname"]=$surname;

$lastFormVars["firstname"]=$firstname;

$lastFormVars["phone"]=$phone;



//Savethearrayasasessionvariable

$_SESSION["lastFormVars"]=$lastFormVars;



//Storethe$errorsarrayasasessionvariable

$_SESSION["errors"]=$errors;



//Relocatetothephonebookform

header("Location:example.10-5.php");

exit;

}



//Ifwemadeithere,thenthedataisvalid

if(!mysql_select_db("telephone",$connection))

showerror();



//Insertthenewphonebookentry

$query="INSERTINTOphonebookVALUES

(NULL,'{$surname}','{$firstname}','{$phone}')";



if(!(@mysql_query($query,$connection)))

showerror();



//Findoutthephonebook_idofthenewentry

$phonebook_id=mysql_insert_id();



//Destroythesession

session_destroy();



//Showthephonebookreceipt



header("Location:example.8-5.php?status=T&phonebook_id={$phone

?>



10.3.3ThePhonebookEntryFormScript

Nowlet'sturntothechangesrequiredforthescriptthat

generatesthephonebookentryformshowninExample8-7.In

thelastsection,wesetuptwosessionvariables:

$_SESSION["errors"]toholdanassociativearrayoferror

messagesfoundbythevalidationscript,and

$_SESSION["lastFormVars"]toholdanassociativearrayfilled

withtheformvalues.Bothsessionvariablesarereadand

incorporatedintoanewforminthissection.



10.3.3.1Displayingpreviouslyenteredform

values



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

3 Case Study: Using Sessions in Validation

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

×