Tải bản đầy đủ - 0 (trang)
7 Case Study: Adding a New Wine

7 Case Study: Adding a New Wine

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

Now,wecanuseanINSERTINTOstatementtocreatethebasic

rowforthewineinthewinetable:



INSERTINTOwineSETwine_id=1049,wine_name='CurryHill',year

description='Abeautifulmaturewine.Idealwithredmeat.';



Thiscreatesanewrowandsetsthebasicattributes.The

wine_idissettothe1048+1=1049.Theremaining

attributes(thewine_typeidentifier,thewinery_ididentifier,

andthevarietiesinthewine_varietytable)requirefurther

queryingandthensubsequentupdates.

Thesecondstepistosetthewinery_idforthenewwine.We

needtosearchfortheRowleyBrookWinerywinerytoidentify

thewinery_id:



SELECTwinery_idFROMwineryWHEREwinery_name='RowleyBrookWi



Theresultreturnedis:

+-----------+

|winery_id|

+-----------+

|298|

+-----------+



1rowinset(0.00sec)



Wecannowupdatethenewwinerowtosetthe

winery_id=298:

UPDATEwineSETwinery_id=298WHEREwine_id=1049;



Thethirdstepissimilartothesecond,andistosetthe

wine_typeidentifierinthewinetable.Youcandiscoverthe

wine_type_idforaRedwineusing:

SELECTwine_type_idFROMwine_typeWHEREwine_type="Red";



Thisreportsthat:

+--------------+

|wine_type_id|

+--------------+

|6|

+--------------+

1rowinset(0.01sec)



Now,youcansettheidentifierinthewinetable:



UPDATEwineSETwine_type=6WHEREwine_id=1049;



Thefourthstepistosetthevarietyinformationforthenew

wine.Weneedthevariety_idvaluesforCabernetandMerlot.

Thesecanbefoundwithasimplequery:

SELECT*FROMgrape_variety;



Inpart,thefollowingresultsareproduced:

+------------+------------+

|variety_id|variety|

+------------+------------+

|1|Riesling|

|2|Chardonnay|

|3|Sauvignon|

|4|Blanc|

|5|Semillon|

|6|Pinot|

|7|Gris|

|8|Verdelho|

|9|Grenache|



|10|Noir|

|11|Cabernet|

|12|Shiraz|

|13|Merlot|



Cabernethasvariety_id=11andMerlotvariety_id=13.We

cannowinserttworowsintothewine_varietytable.Because

Cabernetisthefirstvariety,setitsID=1,andID=2forMerlot:



INSERTINTOwine_varietySETwine_id=1049,variety_id=11,id=1;



INSERTINTOwine_varietySETwine_id=1049,variety_id=13,id=2;



Thefinalstepistoinsertthefirstinventoryrowintothe

inventorytableforthiswine.Thereare24bottles,withaperbottlecostof$14.95:



INSERTINTOinventorySETwine_id=1049,inventory_id=1,on_hand

cost=14.95,date_added="04/03/01";



We'vefinishedinsertingthewineintothedatabase.Now,to

conclude,let'sretrievethedetailsofthewinetomakesure

everythingisasitshouldbe.We'llretrievethewinename,its

year,thewinery,thevarieties,thewinetype,anditscost.

Here'sthequery:



SELECTyear,wine_name,winery_name,variety,wine_type.wine_ty



FROMwine,winery,wine_variety,grape_variety,wine_type,in

WHEREwine.wine_id=1049AND

wine.wine_id=wine_variety.wine_idAND

wine_variety.variety_id=grape_variety.variety_idAND

wine.wine_type=wine_type.wine_type_idAND

wine.winery_id=winery.winery_idAND

wine.wine_id=inventory.wine_id

ORDERBYwine_variety.id;



TheWHEREclauselookscomplicated,butitjustjoinstogetherall

ofthetablesintheFROMclausebymatchinguptheidentifier

attributesandspecifieswewantforwine#1049.Here'sthe

output:



+------+------------+---------------------+----------+---------



|year|wine_name|winery_name|variety|wine_typ



+------+------------+---------------------+----------+---------



|1996|CurryHill|RowleyBrookWinery|Cabernet|Red



|1996|CurryHill|RowleyBrookWinery|Merlot|Red



+------+------------+---------------------+----------+---------



2rowsinset(0.01sec)



Tworowsarereturnedbecausetherearetwovarietiesforthis

wineinthewine_varietytable.

We'venowcoveredasmuchcomplexqueryinginSQLaswe

needforyoutodevelopmostwebdatabaseapplications.You'll

findadiscussionofadvancedfeaturesyoucanuseinChapter

15.Beginninginthenextchapter,weshowyouhowtoinclude

SQLstatementsinPHPscriptstoautomatequeryingandbuild

webdatabaseapplications.



Chapter6.QueryingWebDatabases

Thischapteristhefirstofeightthatintroducepracticalweb

databaseapplicationdevelopment.Inthefirstsection,we

introducethebasicsofconnectingtotheMySQLserverwith

PHP.WedetailthekeyMySQLfunctionsusedtoconnect,query

databases,andretrieveresultsets,andwepresentthefivestepprocessfordynamicallyservingdatafromadatabase.In

thesecondsection,weshowyouhowtodrivethequeriesby

userinputfromanHTMLformandbyclickingonhypertext

links.

Thefirstsectionofthischapterintroducesyoutothefollowing

techniques:

Usingthefive-stepwebdatabasequeryingapproachto

developdatabase-drivenqueries

UsingtheMySQLlibraryfunctionsforqueryingdatabases

HandlingMySQLservererrorsduringdevelopment

Usingincludeandrequirefilestomodularizedatabasecode

Afterwe'vecoveredthebasics,thesecondsectionintroduces

youtousinguserdatainthequeryingprocess.Weshowyou

thefollowingtechniques:

Passingdatafromawebbrowsertoawebserver

Accessinguserdatainscripts

Securinganapplication



Queryingdatabaseswithuserdata

ThefinalsectionisaMySQLfunctionreferencethatexplains

eachlibraryfunctionindetail.

Thefocusofthischapterisdatabaseserveranduser

interaction,notpresentationinthebrowser.Presentationisa

subjectofChapter7.Extendedexamplesofqueryingthatuse

thetechniquesofChapter6andChapter7canbefoundin

Chapter16toChapter20.



6.1QueryingaMySQLDatabaseUsingPHP

InPHP,libraryfunctionsareprovidedforexecutingSQL

statements,aswellasformanagingresultsetsreturnedfrom

queries,errorhandling,andcontrollinghowdataispassedfrom

thedatabaseservertothePHPengine.Weoverviewthese

functionshereandshowhowtheycanbecombinedtoaccess

theMySQLserver.

Atthetimeofwriting,PHP4.3andMySQL4.0werethestable

releases.TheMySQLlibraryfunctionsthatarediscussedhere

workwiththoseversions.ThePHP5MySQLlibraryfunctions

alsoworkwithMySQL4.0.

However,theMySQLfunctionsdiscussedheredonotworkwith

thealphareleaseofMySQL4.1.Instead,anewimproved

libraryisbeingdevelopedforMySQL4.1,anditisintendedto

bepartofPHP5inadditiontotheregularlibrary.An

introductiontothislibraryisincludedasAppendixH.



6.1.1OpeningandUsingaDatabaseConnection

Inthissection,weintroducethebasicPHPscriptingtechniques

toqueryaMySQLserverandproduceHTMLfordisplayinaweb

browser.

ConnectingtoandqueryingaMySQLserverwithPHPisafivestepprocess.Example6-1showsascriptthatconnectstothe

MySQLserver,usesthewinestoredatabase,issuesaqueryto

selectalltherecordsfromthewinetable,andreportsthe

resultsaspre-formattedHTMLtext.Theexampleillustratesfour

ofthekeyfunctionsforconnectingtoandqueryingaMySQL

databasewithPHP.Eachfunctionisprefixedwiththestring

mysql_.



Example6-1.ConnectingtoaMySQLdatabase

withPHP


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

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








Wines








//(1)Openthedatabaseconnection

$connection=mysql_connect("localhost","fred","shhh");



//(2)Selectthewinestoredatabase

mysql_select_db("winestore",$connection);



//(3)Runthequeryonthewinestorethroughtheconnection

$result=mysql_query("SELECT*FROM

wine",$connection);



//(4)Whiletherearestillrowsintheresultset,fetcht

//rowintothearray$row

while($row=mysql_fetch_array($result,MYSQL_NUM))

{



//(5)Printouteachelementin$row,thatis,printthe

//theattributes

foreach($rowas$attribute)

print"{$attribute}";



//Printacarriagereturntoneatentheoutput

print"\n";

}

?>





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

7 Case Study: Adding a New Wine

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

×