Tải bản đầy đủ - 0 (trang)
1 Database Inserts, Updates, and Deletes

1 Database Inserts, Updates, and Deletes

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

->surnameCHAR(50)NOTNULL,

->firstnameCHAR(50)NOTNULL,

->phoneCHAR(20)NOTNULL,

->PRIMARYKEY(phonebook_id)

->)type=MyISAM;

QueryOK,0rowsaffected(0.00sec)



We'vecreatedaphonebook_idattributethatistheprimarykey

touniquelyidentifyeachrowinthetableandwe'veusedthe

auto_incrementmodifierwithit.AswediscussedinChapter5,

insertingNULLintoanauto_incrementPRIMARYKEYattribute

allocatesthenextavailablekeyvalue,andweusethisfeature

inourscript.

Wealsoneedanewuserwhocanaccessthenewdatabase.To

setoneupwiththerightprivileges,youcanusethesame

approachusedinAppendixAthroughAppendixCtoconfigure

MySQL.IntheMySQLcommandinterpreter,type:



mysql>GRANTSELECT,INSERT,UPDATE,DELETE,LOCKTABLESONtel

->fred@127.0.0.1IDENTIFIEDBY'shhh';

QueryOK,0rowsaffected(0.00sec)



Replacefredandshhhwiththeusernameandpasswordyou

wanttouse(anddothesamelaterinallofthePHPscriptsin

thischapter).



NowweneedanHTMLformthatallowsuserstoprovidethe

detailstocreateanewrowinthephonebooktable.Example81showssuchaformthat'slaidoutforpresentationusinga

tableelement.Itcollectsthreevaluesintothreeinputelements

withthenamessurname,firstname,andphone,andituses

theGETmethodtopassvaluestothescriptexample.8-2.php.



Example8-1.AnHTMLformtocapturethename

ofanewregion


"-//W3C//DTDHTML4.01Transitional//EN"

"http://www.w3.org/TR/html401/loose.dtd">








AddaPhonebookEntry





AddaPhonebookEntry





















Surname:



Firstname:



Phonenumber:
















Example8-2showsthescriptthataddsthenewdatatothe

phonebooktable.Itworksasfollows:ifasurname,firstname,

andphonenumberaresuppliedbytheuser,anINSERTSQL



statementispreparedtoinsertthenewrow;themysqlclean()

function(andthedb.incincludefilewhereit'sstored)are

discussedinChapter6.AsdescribedinChapter5,inserting

NULLresultsintheauto_incrementmodifierallocatingthenext

availablekeyvalue.Ifanyofthevaluesaremissing,itredirects

backtotheformusingtheheader()functionthat'sdiscussedin

Chapter6.



Example8-2.Ascripttoinsertanewphonebook

entry


require"db.inc";

require_once"HTML/Template/ITX.php";



//Testforuserinput

if(!empty($_GET["surname"])&&

!empty($_GET["firstname"])&&

!empty($_GET["phone"]))

{



if(!($connection=@mysql_connect("localhost","fred","shh

die("Couldnotconnecttodatabase");



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



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

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



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

showerror();



//Insertthenewphonebookentry

$query="INSERTINTOphonebookVALUES

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



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

showerror();



$template=newHTML_Template_ITX("./templates");

$template->loadTemplatefile("example.8-3.tpl",true,true);

$template->setCurrentBlock();

$template->setVariable("SURNAME",$surname);

$template->setVariable("FIRSTNAME",$firstname);



$template->setVariable("PHONE",$phone);

$template->parseCurrentBlock();



$template->show();

}//ifempty()

else

//Missingdata:Gobacktothe


header("Location:example.8-1.html");

?>



Ifthequeryissuccessful,thenatemplatethatshowsthe

resultsisloadedanddisplayed(thisisdiscussednext).Ifan

erroroccurs,errorhandlingusingthemethodsdescribedin

Chapter6isused.

WeuseaPEARITtemplatefileinExample8-2.Thetemplate

fileisstoredasexample.8-3.tplandshowninExample8-3.This

templatehasthreeplaceholderstoshowthedetailsofthenew

row.ThePEARtemplatepackageisexplainedinChapter7.



Example8-3.ThetemplatefileusedinExample

8-2


"-//W3C//DTDHTML4.01Transitional//EN"



"http://www.w3.org/TR/html401/loose.dtd">








AddedaPhonebookEntry





AddedaPhonebookEntry



















Surname:

{SURNAME}

Firstname:

{FIRSTNAME}

Phonenumber:

{PHONE}









Mostwriteoperationscanuseaformatsimilartothatof

Example8-2.Inparticular,wheredatabasechangesare

reasonablyinfrequentandcanbeperformedinonestep,most

ofthemorecomplexissueswedescribelaterinSection8.2can

beignored.However,asnotedearlier,Example8-2doeshave

oneundesirablesideeffectthatiscommoninwebdatabase

applications.Theproblemisn'treallyrelatedtomodifyingthe

databasebutrathertothestatelessnessoftheHTTPprotocol.

Wediscussthissideeffect,thereloadproblem,andaneffective

solutioninthenextsection.



8.1.1ReloadingDataandRelocationTechniques

SimpleupdatesusingtheapproachshowninExample8-2are

susceptibletoacommonproblemofthestatelessHTTPprotocol

thatwecallthereloadproblem.Considerwhathappenswhen

ausersuccessfullyentersanewphonebookentry,andclicks

theSubmitbutton.ThecodeinExample8-2isexecuted,anew

rowisinsertedinthephonebooktable,andasuccessmessage

isdisplayed.Sofar,everythingisgoingaccordingtoplan.

Considernowwhathappensiftheuserreloadsthesuccess



messagepagewiththeReloadorRefreshbuttoninthebrowser.

Thevariablesandvaluesareresubmittedtothesamescript,

andanotheridenticalrow(exceptforthephonebook_idvalue,

whichisautomaticallyincremented)isaddedtothephonebook

table.Thereisnowayinthisexamplethatthefirstclickofthe

Submitbuttontoaddthefirstrowcanbedistinguishedfroma

secondactionthatsendsthesamevariablesandvaluestothe

script.ArepresentationofthereloadproblemisshowninFigure

8-1.



Figure8-1.Thereloadproblem



Thereloadproblemoccursinmanysituations.Actionsthatre-requesta

documentfromtheserverincludepressingtheReloadorRefresh

buttons,printing,savingtheURLinthebrowserandreturningtothe

pageusingabookmarkorfavorite,usingtheBackorForwardbuttons,

pressingtheEnterkeyintheURLLocationentrybox,andresizingthe

browserwindow.



Thereloadproblemisn'talwaysasignificantproblem.For

example,ifyouusetheSQLUPDATEstatementtoupdate

phonebookdetails,andthevaluesareamendedwiththesame

correctvaluesrepeatedly,thereisnodataduplication.Similarly,

ifarowisdeletedandtheuserrepeatstheoperation,therow

can'tbedeletedtwice.However,whilesomeUPDATEandDELETE

operationsarelesssusceptibletothereloadproblem,awelldesignedsystemavoidstheproblemaltogether.Avoidance

preventsuserconfusionandunnecessaryDBMSactivity.We

discussasolutioninamoment.

TheHTTPPOSTmethodisalittlelesssusceptibletothereload

problemthantheGETmethod.Ifauseragainretrievesthe

scriptafterthefirstdatabasechange,thebrowsershouldask

theuseristhey'resuretheywanttorepeattheaction.Mostof

thetime,thiswillpreventtheproblembecausetheuserwill

clickCancel.However,iftheuserdoesclickOK,thedatabase

operationwillberepeatedandcausethereloadproblem.

AsolutiontothereloadproblemisshowninFigure8-2.Itis

basedontheHTTPLocation:header,thesameheaderusedfor

one-componentqueryinginChapter6.



Figure8-2.Solvingthereloadproblemwitha

redirectiontoareceiptpage



Thereloadsolutionworksasfollows:

1. Theusersubmitstheformwiththevariablesand

valuesforadatabasewriteoperation(anSQLINSERT,

UPDATE,orDELETE).

TheSQLwriteoperationisattempted.

Whetherornotthemodificationissuccessful,anHTTP

Location:headerissenttothebrowsertoredirectthebrowser

toanew,receiptpage.

HTTPGETencodedvariablesandvaluesareusuallyincluded

withtheLocation:headertoindicatewhethertheactionwas

successful.Additionally,texttodisplaymightbesentaspartof

theredirectionURL.



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

1 Database Inserts, Updates, and Deletes

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

×