Top Banner
64

Learning Php and Mysql

Nov 05, 2015

Download

Documents

rtb101

Learning Php and Mysql.pdf
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • LEARNINGSTARTSWITHVIEWINGTHEWORLDDIFFERENTLY.

    Knowledgeflow-Amobilelearningplatformprovidesapps,eBooksandvideotutorials.

    KnowledgeflowbringsyoualearningeBookofLearningPHPandMySQL.ThiseBookisforallinformationtechnology,computerscienceandwebdevelopmentstudentsandprofessionalsacrosstheworld.

    Followuson

    Facebook

    Googleplus

    Twitter

    Formoreinformationvisitusat

    Knowledgeflow.in

    knowledgeflowapps.blogspot.inThankyouforusingKnowledgefloweBooks

  • LEARNINGPHPANDMYSQL1.IntroductionofPHP

    2.FeaturesofPHP

    3.VariablesandArrays

    4.Operators

    5.Functions

    6.IntroductionofSQL

    7.OperatorsandConditionsofSQL

    8.Queries,Sub-queriesand3VL

    9.DataControlandDrawbacks

    10.PHPwithMySQL

    11.CreateandInsertinMySQLusingPHP

    12.UpdateandRetrieveinMySQLusingPHP

    13.DeleteinMySQLusingPHP

    14.MoreeBooksandApps

  • DisclaimerThiseBookcontentsisforinformationalandstudypurposesonly.TheKnowledgeflowmakesnoclaims,promises,orguaranteesabouttheaccuracy,completeness,oradequacyofthecontentsofthiseBookandnolegalliabilityorotherresponsibilityisacceptedbyKnowledgeflowforanyerrors,omissions,orstatementsonthiseBook.

  • IntroductionPHPisoriginallyapersonalizedhomepagei.e.Nowusedasaserversidescriptinglanguage.Itisusedandexecutedonserver.Itwasintroducemainlyforwebdesigningpurpose.PHPwasactuallycreatedRasmusLerdorfin1994.Atpresentitishypertextpreprocessor.Itisusedforserversidewebdevelopment.Itcanbeusedasacommandlinescripter.ItcanbeusedasaGUIfortheclient.IthelpedmanysoftwareframeworkstoprovideRADi.e.rapidapplicationdevelopment.Itprovidesdynamiccontentstoclient.

    LogoofPHP

    HistoryofPHP

    PHPdevelopmentwasstartedbyRasmusLerdorfin1994.HestartedkeepinghispersonalhomepagetowriteaseriesofCGIi.e.commongatewayinterfaceinC.In1997theparserwasrewrittenbyZeevSuraskiandAndyGutmanswhichleadtotheexistenceofbasicPHP.Therehadbeenonlytwostablereleaseswithallsecurityandbugfixes.PHPhasamascotwhichisblueelephantwhichwasdesignedbyVincentPointer.

    FutureofPHP

    Theversion5.0and5.5whichwerereleasedarerespectivelysupportedtilldateJune2016andAugust2017.Version7.0willbereleasedinmidOctoberof2015andwillbesupportedtill2018.Version7.0isreleasedwiththefeatureofuniformvariablesyntax,bitwiseshiftconsistencyacrossplatformandreturntypedeclaration.Version7.0willcomplementitsalreadyexistingparametertypedeclaration.Version7.0willalsorectifyallthealreadyexistinglongtimeflawsofPHP.

  • LicensingofPHP

    PHPisafreesoftwarereleasedfreeofcostsoftware.Itslicensestatesthat-productderivedfromPHPmaynotbecalledPHP,normayPHPnameshouldbeappearedwithoutpriorwrittenpermissionfromgroup@php.net.YoumayindicatethatyoursoftwarehadbeenworkingwithPHPbysayingFOOinsteadofPHP.ShouldnotstateitasPHPFOOorphpfoo.

  • FeaturesofPHPTheyareasfollows.

    Serverside-PHPwontexecutewithinthelocalmachineswebbrowser,insteaditwillbeexecutedinthewebserver.Crossplatformed-ThisfeatureallowsthePHPscripttorunandexecutedonanyoperatingsystemandwebserver.HTMLembeddedlanguage-ThismeansthecommandsandstatementofPHPisalreadyembeddedintheHTMLdocument.

    WorkingofPHP

    PHPsupportsmanydatabasesanditisopensourcesoftwarewhichisfreetodownloadanduse.

    UsesofPHP

    PHPcanbeusedforcreationofdynamicwebsite.Forbuildingtemplatethatwouldmakethesitemaintenanceeasy.Forcreationofgraphicsonthefly.Formaintainingthedifferentiationofthetypeofcontenttobeservedonthebasisoftheusersbrowser,IPaddress,dateandtimeandvariousotherdetails.Forconductingasurveyonline.Toconnectdatabaseswiththeweb.Fore.g.oracleandMySQL.Helpsinprovidingalinkofcommunicationwithexternalweb.

  • ItperformsreadandprocessXML.

    SimplescriptinginPHP

    ThePHPstatementisfollow-

    Thiswoulddisplaythemessagehellointhewindowbrowser.

    ThePHPprintfunctiondisplaysthevaluewiththeparenthesisasoutputinnewwindow.

    ImportantthingsaboutPHPscripts-

    PHPiscasesensitive.PHPstatementsarestatedbetween.Italwaysendswithsemi-colon.Commentscanbeaddedusing//inthebeginningoftheline.PHPfileshouldnothave.htmlextension.Fileshouldhave.PHPextension.Ifthefiledonthave.PHPextensionnorhas.htmlextensionthefilewontfound,parsedandexecuted.

    AdvantageofPHPwithhighsecurityi.e.safemode-

    Theownershipshouldbesameforthescriptbeingexecutedandfilefromwhichitisreadorwritten.

  • ThedirectoryshouldbeownedbytheownerofthePHPscript.PHPcannotexecuteexternalprogramswhicharenotfromthesystem.

  • VariablesVariablesareusedtostorevalueslikestringsnumbersetc.Whenavariableisdeclared,itcanbeusedagainandagaininyourscript.SymbolusedtorepresentPHPvariablesis$.

    Syntax

    $var_name=value;

    ThereisnoneedtospecifyinPHPthatthevariableusebelongtowhichdatatype.PHPconvertsthevariableintocorrectdatatype.Avariablenamecanalsocontainalphanumericalcharactersbutitshouldnotcontainspace.

    Example

    Predefinedvariables

    TheworkenvironmentthatisbeenusedbyyouisbeenaccessedbythePHPscript.Suchvariablesarestoredinaspecialhashdatalike$_ENVand$_SERVER.Thesevariablescanbeusedonlyonetwoincountatatime.

    Example

    Example2

  • print(yourinternetaddressis$_SERVER[REMOTE_ADDR]);

    ?>

    Variablefromexternalsource

    Htmlforms(GETandPOST)

    InformationfromtheformwhensubmittedtoPHPisautomaticallymadeavailabletotheparticularscript.

    Example

    Name-

    Email-

  • ArraysArrayisanorderedmapactuallyinPHP.Thistypeofoptimizationissothatitcanhaveseveraldifferentuses.Arraysvaluecanbearrays,treesandevenmultidimensionalarrays.

    Example

    Array(

    Key=>value,

    Keya=>value2,

    Keyb=>value3,

    .

    )

    Arraycanalsobemadeusingakey/valuepaircombination.Thesearealsoconsideredasassociativearraysandhashes.Aneasywaytocompresshashworkistothinkitasatable.

    Example

    Country(Key) City(Value)

    Cambodia PhnomPenh

    Lebanon Beirut

    Cuba Habana

    Indonesia Jakarta

    Finland Helsinki

    Table

  • Finland=>Helsinki);

    Print($capital[Cambodia]);

    ?>

    Predefinedconstantofarray

    CASE_LOWERCASE_UPPERSORT_ASCSORT_DESCCOUNT_NORMALCOUNT_RECURSIVEEXTR_SKIPEXTR_OVERWRITEEXTR_IF_EXISTS.

  • OperatorsArithmeticoperators

    Example Name Result

    -$a Negation Oppositeof$a

    $a+$b Addition Sumof$aand$b

    $a-$b Subtraction Differenceof$aand$b

    $a*$b Multiplication Productof$aand$b

    $a/$b Division Quotientof$aand$b

    $a%$b Modulus Remainderof$aand$b

    Thedivisionoperatorwouldreturnfloatvalueunlessthetwooperandsareintegers.

    Example

    Assignmentoperator

    TherearetwotypesofassignmentoperatorswhicharecommonlyusedinPHP.Thesearerepresentedas=and=>.

  • Example

    Bitwiseoperator

    Itallowsevaluationandmanipulationofaspecificbit.

    Example Name Result

    $a&$b And Aresetinboth$aand$b

    $a|$b Or Aresetineither$aor$b

    $a^$b Xor Notinboth

    ~$a Not Aresetin$aarenotset

    $a $b Shiftleft Shiftsbitsof$a$btoleft

    $a $b Shiftright Shiftbitsof$a$btoright

    Comparisonoperator

    Itallowsthecomparisontobedonebytheuse.

    Example Name Result

    $a==$b Equal Trueif$a=$b

    $a===$b identical Trueif$a=$b

    $a!=$b Notequal Trueif$a$b

    $a$b Notequal Trueif$a$b

    $a!==$b Notidentical Trueif$a$b

    $a

  • $b

    $a>$b Greaterthan Trueif$agreaterthan$b

    Errorcontroloperator

    Itisrepresentedby@.Usingthisitwillignoreanyerrorthatisbeenintendedbytheexpression.

    Example

    Executionoperator

    Supportsexecutionoperator:backticks().Useofbacktickisidenticaltotheshell_exec().

    Example

    Incrementdecrementoperator

    Theyarepreandpostincrementdecrementoperatorincstyle.

    Example Name Effect

    ++$a Pre-increment Increasesbyone

    $a++ Post-increment Returns,thenincreases

    $a Pre-decrement Decreasesthenreturns

    $a Post-decrement Returnsthendecreases

  • Logicaloperator

    Theuseoftwodifferentvariablesistogetdifferentprecedenceasresult.

    Example Name Result

    $aand$b And Trueifbotharetrue

    $aor$b Or Trueifeitheristrue

    $axor$b Xor Trueifeitheristrue

    !$a Not Trueif$aisnottrue

    $a&&$b And Trueifbotharetrue

    $a||$b Or Trueifeitheristrue

  • FunctionsFunctionsaregroupsofPHPstatementsgroupedtogetherthatareorcanbeusedoverandoveragain.Ithasmorethan1000builtinanduserdefinedfunction.Functiondontexecuteimmediately.Functionsonlyexecutewhenucallthem.Statementmaycontainmultiplefunctions.

    User-definedfunction

    Itcanbedefinedasshownintheexample.

    Example

    Functionargument

    Throughaargumentlisttheinformationcanbepassedtothefunction.Thisisacommadelimitedlistofexpression.

    Example

    Returningvalues

  • Valuesarereturnedusingtheoptionalreturnstatement.Anytypecanbereturned,includingarraysandobjects.

    Example

    Internal(built-in)function

    Thesearealreadysetinthelibrary.TherealsofunctionthatrequirescertainspecifiedPHPextensioncompiled.

    Example

    Tocreateimagefunctionweuseimagecreatetruecolor().

    Anonymousfunction

    Thisfunctionisalsoknownasclosure,thishasnospecificname.

    Example

  • SQLSQLstandsforstandardquerylanguagewhichisusedtoaccessdatabases.ItalsousedtomanipulatedatabaseanditisanANSIstandard. MySQListhewidelyusedopensourceRelationaldatabasemanagementsystem.MySQLisgenerallyRDBMSbeingusedfordevelopingweb-basedsoftwareapplicationsandyoucanaddSQLqueriestotheMySQLdatabasetoinsert,retrieve,updateordeletedata.

    LogoofMySQL

    History

    Itwasdevelopedin1970atIBMwithDonaldD.ChamberlinandRaymondF.Boyce.ItwasfirstnamedasSEQUEL.ThiswassoldtoUSNAVY,C.I.AandU.S.Governmentagenciesafteritspotentialwasrecognized.

    UsesofSQL

    Usedtoexecutequeryagainstdatabase.Toretrieveadatafromdatabase.Toinsertrecord.Toupdaterecord.Todeleterecord.Tocreateanewdatabase.Tocreatenewtablesindatabase.Tocreatevariousstorageproceduresindatabase.Tocreatevariouskindofviewsinadatabase.Tocreatepermissionsforthefunctioningofvariousproceduresontablesandviews.

  • HowtouseSQLinwebsite

    OneoftheRDMSPROGRAM.UseofPHPorASP.UseofSQLforthedatatoberetrieved.UseHTML/CSS.

    MostimportantSQLcommand

    SelectToextractanyneededordesiredrecordordatafromdatabase.UpdateToupdateormodifyanydatainthedatabase.DeleteTodeleteorremoveanydatafromdatabase.InsertintoToaddorinsertintodatabase.CreatedatabaseTocreateorstartanewdatabase.AlterdatabaseTomodifyoreditdatabase.DroptableToremoveordeleteatableindatabase.CreatesindexTocreateanewindex.Dropindex-Toremoveordeleteanindex.

    SyntaxofSQL

    SELECT*FROMCustomers;

    SQLisnotcasesensitive.ThismeansbothselectandSELECThavethesamemeaning.

    VariouslanguageelementsofSQLlanguages

    ClausesExpressionPredicateQueryStatementInsignificantwhitespace

    LanguageelementsofSQL

  • OperatorsinSQLSQLoperatorsareasfollows.

    Operator Description Example

    = Equalto John=author

    Notequalto Deptheight

    > Greaterthan 100>6

    < Lessthan 6

  • ConditionsSQLexpression-

    Case-Itisoneofthesearchingtechniquesoffindingthematchingcase.ItwasusedinSQL-92.

    Example

    CASEWHENN>0

    THENPOSITIVEVALUE

    WHEN

  • THENthreeORANGE

    WHEN4

    THENfourORANGES

    ELSE

    CANNOTCOUNTTHATVALUE.

    Else-Whenthewhenconditionisnotsatisfiedtheprocessleadstoanotheroption,thatisdefinedaselsestatement.

    Example

    WHEN5

    THENFIVEORANGES

    ELSE

    CANNOTCOUNTTHATVALUE.

    End-Itisusedtoterminatetheprogramwhichleadsthesystemtostoptheexecution.

    Example

    CASEx

    WHEN1

    THENCOUNT1

    WHEN2

    THENCOUNT2

    ELSEERROR

    END

  • QueriesQueryisthemostcommonlyusedandoneofthekeyoperationsinSQL.ItisdeclaredusingSELECTstatement.Itprovidesuserwithvariousmethodstodescribeandshowhis/herdesireddata.An*isusedtoshowthatthequeryshouldreturnallcolumnsoftheparticularthatisqueried.ItisarequestinformationmethodusedintheSQLthereforeitisakeyfactorandmostlythebackboneoftheSQL.

    MySQLquerywindow

    VariousclausesandkeywordsusedinSQLareasfollows.

    FROMclause-Thisshowsfromwhereorwhichtabletoretrievedatafrom.Whereclause-Thisincludesapredicateforcomparisonthishelpsinrestrictingoftherowthatisbeenreturnedbythequery.Groupbyclause-Usedtoprojectrowsthatareidenticalorhavecommonvalue.Havingclause-ItisusedinfiltrationofrowwhereitcanbecombinedwithGroupbyclause.Orderbyclause-Itsortsorarrangesthedatainaformitsneededtobearranged.

    Example

    SELECTBooktitleASTIM,

    COUNT(*)ASAuthors

    FROMBook

  • JOINBook_TIM

    ONBook.isbn=Book_author.isbn

    GROUPBYBook.title

    Output

  • Sub-QueriesThesearenestedqueries.Aquerythatisinanotherqueryandthisisembeddedwithinthewhereclause.Sub-Queriesareusuallyusedtoreturndatawhichwillbefurtherusedinthemainquery.

    RulesofSub-queries

    Ithastobeenclosedwithinparenthesis.ItcanhaveonlyonecolumninSELECTclause.ItisnotallowedtouseODERBYquerywhereasinsteadofthatGROUPBYisused.Itcannothaveimmediateenclosureinasetfunction.

    Useofsub-queries

    Itisusedtojoinonetablewithothertablesoperation.Thisalsoprovidesfasterremedies.Thisprovidesahierarchicalexecution.Subquerycanusevaluesfromqueryoutside,thesearecorrelatedsubquery.

    Sub-Query

    Example

    SELECTisbn,

    Name,

    Price,

    FROMBook

    WHEREpricequery($sql)===TRUE)

    {echoDatabasecreatedsuccessfully;}

    else

    {echoErrorcreatingdatabase:.$conn->error;}

    $conn->close();

    ?>

    PDO

  • catch(PDOException$e)

    {

    echo$sql..$e->getMessage();

    }

    $conn=null;

    ?>

    Syntaxrules

    QueryhastobequotedinPHP.Numericvaluemustbeavoided.NULLvalueshouldnotbequoted,itshouldbeavoided.

    Highefficientstatements

    Preparationstatement-IsanSQLstatementusetocreateandsendatemplatetotheparticulardatabase.Executestatement-Isusedtobindalltheretrievedvaluesandtoexecutethem.

  • CreatingMySQLdatabaseusingPHPAdminshouldbeprivilegetocreatedatabase.PHPusesmysql_queryforcreationoftheSQLdatabase.Thishastwoparameterfunctioningwhichistruewhencreationissuccessfulandfalsewhenafailureoccurs.

    Syntax

    Boolmysql_query(sql,connection);

    Example

  • InsertofdatainMySQLdatabaseusingPHPTheinsertstatementcarriesoutthefunctionusingPHPbyusingquerystatementmysql_queryfortheSQLINSERTstatement.

    Example

  • UpdateinMySQLDatabaseusingPHPForupdatinginMySQLthereisaneedofthecommandtobecarriedoutthatisSQLUPDATEstatementthroughPHPfunctionmysql_query.

    Example

    UpdateaRecordinMySQLDatabase

  • $retval=mysql_query($sql,$conn);

    if(!$retval)

    {

    die(Couldnotupdatedata:.mysql_error());

    }

    echoUpdateddatasuccessfully\n;

    mysql_close($conn);

    }

    else

    {

    ?>

  • TheupdatingperformedusingPHPinMySQLprovidesmoreefficiencyandexception.

  • RetrievalinMySQLDatabaseusingPHPRetrievalinSQListermedasfetchthereforetoperformretrievalinSQLusingPHPacodeisbeeninusewhichisasfollow

    Syntax

    Mysql_fetch_arrays()

    Example

  • EMPSALARY:{$row[emp_salary]}.

    ;

    }

    echoFetcheddatasuccessfully\n;

    mysql_close($conn);

    ?>

  • DeletingofMySQLDatabaseusingPHPThedatabaseonceisnotneededandtheuserdontwanttohaveitanymoreorwanttofreespacethentheusercanpassastatementthatwouldstatetodeletethedatabasethroughthemysql_queryfordeletionofdata.ThetermusedinSQLfordeleteisdrop.

    Example

  • DeletingofdatafromMySQLusingPHPWhenintendedortheuserwantstodeleteanydatafromtheMySQLdatabaseusingPHPtheusercanpassastatementstatingthatthroughmysql_query.

    Example

    DeletefromMySQLDatabase

  • {Die(couldnotdeletedata:.mysql_error());

    }

    EchoDeletionsuccessful\n;

    mysql_close($conn);

    }

    else

    {

    ?>

  • YoucantakebackupoftheSQLdatabaseusingfollowingmethods.

    UsingcommandofSQLthroughPHP.UsingmysqldumpwiththehelpofPHP.ByusingaphpMyAdminuserinterface.

  • Knowledgeflow:moreeBooksandAppsGetmoreGooglePlayBooksGetmoreeBooksGetmoreappsfromGooglePlaystoreGetmoreappsfromAmazonappstore