Download Learning PHP and MySQL: by Knowledge flow

Document related concepts

Tandem Computers wikipedia , lookup

Relational algebra wikipedia , lookup

Microsoft Access wikipedia , lookup

Oracle Database wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Concurrency control wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Ingres (database) wikipedia , lookup

Functional Database Model wikipedia , lookup

Database wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Clusterpoint wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Database model wikipedia , lookup

SQL wikipedia , lookup

Relational model wikipedia , lookup

PL/SQL wikipedia , lookup

Transcript
“LEARNINGSTARTSWITHVIEWINGTHEWORLDDIFFERENTLY.”
Knowledgeflow-Amobilelearningplatformprovidesapps,eBooksandvideotutorials.
KnowledgeflowbringsyoualearningeBookofLearningPHPandMySQL.ThiseBook
isforallinformationtechnology,computerscienceandwebdevelopmentstudentsand
professionalsacrosstheworld.
Followuson
Facebook
Googleplus
Twitter
Formoreinformationvisitusat
Knowledgeflow.in
knowledgeflowapps.blogspot.in
ThankyouforusingKnowledgefloweBooks
LEARNINGPHPANDMYSQL
1.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
Disclaimer
ThiseBookcontentsisforinformationalandstudypurposesonly.TheKnowledgeflow
makesnoclaims,promises,orguaranteesabouttheaccuracy,completeness,oradequacy
ofthecontentsofthiseBookandnolegalliabilityorotherresponsibilityisacceptedby
Knowledgeflowforanyerrors,omissions,orstatementsonthiseBook.
Introduction
PHPisoriginallyapersonalizedhomepagei.e.Nowusedasaserversidescripting
language.Itisusedandexecutedonserver.Itwasintroducemainlyforwebdesigning
purpose.PHPwasactuallycreatedRasmusLerdorfin1994.Atpresentitishypertext
preprocessor.Itisusedforserversidewebdevelopment.Itcanbeusedasacommandline
scripter.ItcanbeusedasaGUIfortheclient.Ithelpedmanysoftwareframeworksto
provideRADi.e.rapidapplicationdevelopment.Itprovidesdynamiccontentstoclient.
LogoofPHP
HistoryofPHP
PHPdevelopmentwasstartedbyRasmusLerdorfin1994.
HestartedkeepinghispersonalhomepagetowriteaseriesofCGIi.e.common
gatewayinterfaceinC.
In1997theparserwasrewrittenbyZeevSuraskiandAndyGutmanswhichleadto
theexistenceofbasicPHP.
Therehadbeenonlytwostablereleaseswithallsecurityandbugfixes.
PHPhasamascotwhichisblueelephantwhichwasdesignedbyVincentPointer.
FutureofPHP
Theversion5.0and5.5whichwerereleasedarerespectivelysupportedtilldate
June2016andAugust2017.
Version7.0willbereleasedinmidOctoberof2015andwillbesupportedtill2018.
Version7.0isreleasedwiththefeatureofuniformvariablesyntax,bitwiseshift
consistencyacrossplatformandreturntypedeclaration.
Version7.0willcomplementitsalreadyexistingparametertypedeclaration.
Version7.0willalsorectifyallthealreadyexistinglongtimeflawsofPHP.
LicensingofPHP
PHPisafreesoftwarereleasedfreeofcostsoftware.
Itslicensestatesthat-productderivedfromPHPmaynotbecalledPHP,normay
PHPnameshouldbeappearedwithoutpriorwrittenpermissionfrom
[email protected].
YoumayindicatethatyoursoftwarehadbeenworkingwithPHPbysayingFOO
insteadofPHP.
ShouldnotstateitasPHPFOOorphpfoo.
FeaturesofPHP
Theyareasfollows.
Serverside-PHPwon’texecutewithinthelocalmachineswebbrowser,insteadit
willbeexecutedinthewebserver.
Crossplatformed-ThisfeatureallowsthePHPscripttorunandexecutedonany
operatingsystemandwebserver.
HTMLembeddedlanguage-ThismeansthecommandsandstatementofPHPis
alreadyembeddedintheHTMLdocument.
WorkingofPHP
PHPsupportsmanydatabasesanditisopensourcesoftwarewhichisfreetodownload
anduse.
UsesofPHP
PHPcanbeusedforcreationofdynamicwebsite.
Forbuildingtemplatethatwouldmakethesitemaintenanceeasy.
Forcreationofgraphicsonthefly.
Formaintainingthedifferentiationofthetypeofcontenttobeservedonthebasisof
theusersbrowser,IPaddress,dateandtimeandvariousotherdetails.
Forconductingasurveyonline.
Toconnectdatabaseswiththeweb.Fore.g.oracleandMySQL.
Helpsinprovidingalinkofcommunicationwithexternalweb.
ItperformsreadandprocessXML.
SimplescriptinginPHP
<HTML>
<HEAD>
<TITLE>
</HEAD>
<BODY>
<?
//HELLOINPHP
PRINT(“HELLO”);
?>
</BODY>
</HTML>
ThePHPstatementisfollow<?PRINT(“HELLO”);?>
Thiswoulddisplaythemessage“hello”inthewindowbrowser.
ThePHPprintfunctiondisplaysthevaluewiththeparenthesisasoutputinnewwindow.
ImportantthingsaboutPHPscriptsPHPiscasesensitive.
PHPstatementsarestatedbetween<??>.
Italwaysendswithsemi-colon.
Commentscanbeaddedusing//inthebeginningoftheline.
PHPfileshouldnothave.htmlextension.
Fileshouldhave.PHPextension.
Ifthefiledon’thave.PHPextensionnorhas.htmlextensionthefilewon’tfound,
parsedandexecuted.
AdvantageofPHPwithhighsecurityi.e.safemodeTheownershipshouldbesameforthescriptbeingexecutedandfilefromwhichit
isreadorwritten.
ThedirectoryshouldbeownedbytheownerofthePHPscript.
PHPcannotexecuteexternalprogramswhicharenotfromthesystem.
Variables
Variablesareusedtostorevalueslikestringsnumbersetc.Whenavariableisdeclared,it
canbeusedagainandagaininyourscript.SymbolusedtorepresentPHPvariablesis“$
“.
Syntax
$var_name=value;
ThereisnoneedtospecifyinPHPthatthevariableusebelongtowhichdatatype.PHP
convertsthevariableintocorrectdatatype.Avariablenamecanalsocontainalpha
numericalcharactersbutitshouldnotcontainspace.
Example
<?php
$name=‘Raj’;
$yearborn=1977;
$currentyear=2015;
$age=$currentyear-$yearborn;
Print(“$nameis$ageyearsold”)
?>
Predefinedvariables
TheworkenvironmentthatisbeenusedbyyouisbeenaccessedbythePHPscript.Such
variablesarestoredinaspecialhashdatalike$_ENVand$_SERVER.Thesevariables
canbeusedonlyonetwoincountatatime.
Example
<HTML>
<HEAD><TITLE>Example2</TITLE></HEAD>
<BODY>
<?
print(“hello>”);
print(“youareusing$_SERVER[HTTP_SERVER_AGENT]<br>”);
print(“yourinternetaddressis$_SERVER[REMOTE_ADDR]<br>”);
?>
</BODY>
</HTML>
Variablefromexternalsource
Htmlforms(GETandPOST)
InformationfromtheformwhensubmittedtoPHPisautomaticallymadeavailabletothe
particularscript.
Example
<formaction=“foo.php”method=“post”>
Name-<inputtype=“text”name=“username”/><br/>
Email-<inputtype=“text”name=“email”/><br/>
<inputtype=“submit”name=“submit”value=“submitme!”/>
</form>
Arrays
ArrayisanorderedmapactuallyinPHP.Thistypeofoptimizationissothatitcanhave
severaldifferentuses.Arraysvaluecanbearrays,treesandevenmultidimensionalarrays.
Example
Array(
Key=>value,
Keya=>value2,
Keyb=>value3,
….
)
Arraycanalsobemadeusingakey/valuepaircombination.Thesearealsoconsideredas
associativearraysandhashes.Aneasywaytocompresshashworkistothinkitasatable.
Example
Country(Key)
City(Value)
Cambodia
PhnomPenh
Lebanon
Beirut
Cuba
Habana
Indonesia
Jakarta
Finland
Helsinki
Table
<?php//createthearray(
‘Cambodia’=>‘PhomPenh’,
‘Lebanon’=>‘Beirut’,
‘Cuba’=>‘Habana’,
‘Indonesia=>’Jakarta’,
‘Finland’=>‘Helsinki’);
Print($capital[‘Cambodia’]);
?>
Predefinedconstantofarray
CASE_LOWER
CASE_UPPER
SORT_ASC
SORT_DESC
COUNT_NORMAL
COUNT_RECURSIVE
EXTR_SKIP
EXTR_OVERWRITE
EXTR_IF_EXISTS.
Operators
Arithmeticoperators
Example
Name
Result
-$a
Negation
Oppositeof$a
$a+$b
Addition
Sumof$aand
$b
$a-$b
Subtraction
Differenceof$a
and$b
$a*$b
Multiplication
Productof$a
and$b
$a/$b
Division
Quotientof$a
and$b
$a%$b
Modulus
Remainderof$a
and$b
Thedivisionoperatorwouldreturnfloatvalueunlessthetwooperandsareintegers.
Example
<?php
Echo(5%3).”\n”;
Echo(5%-3).”\n”;
Echo(-5%3).”\n”;
Echo(-5%-3).”\n”;
?>
Assignmentoperator
TherearetwotypesofassignmentoperatorswhicharecommonlyusedinPHP.Theseare
representedas“=”and“=>”.
Example
<?php
$a=($b=4)+5;
?>
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
Lessthan
Trueif$astrictlylessthan
$b
$a>$b
Greaterthan
Trueif$agreaterthan$b
Errorcontroloperator
Itisrepresentedby‘@‘.Usingthisitwillignoreanyerrorthatisbeenintendedbythe
expression.
Example
<?php
$my_file=@file(‘non_existent_file’)
$value=@$cache[$key];
?>
Executionoperator
Supportsexecutionoperator:backticks(“).Useofbacktickisidenticaltotheshell_exec
().
Example
<?php
$output=“ls–al”;
echo“<pre>$output</pre>;
?>
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
Functions
FunctionsaregroupsofPHPstatementsgroupedtogetherthatareorcanbeused
overandoveragain.
Ithasmorethan1000builtinanduserdefinedfunction.
Functiondon’texecuteimmediately.
Functionsonlyexecutewhenucallthem.
Statementmaycontainmultiplefunctions.
User-definedfunction
Itcanbedefinedasshownintheexample.
Example
<?php
Functionfoo($arg_1,$arg_2,…….,$args_n)
Echo“example.\n”;
Return$retval;
}
?>
Functionargument
Throughaargumentlisttheinformationcanbepassedtothefunction.Thisisacomma
delimitedlistofexpression.
Example
<?php
Functiontakes_array($input)
{
Echo“$input[0]+$input[1]=“,$input[0]+$input[1];
}
?> Returningvalues
Valuesarereturnedusingtheoptionalreturnstatement.Anytypecanbereturned,
includingarraysandobjects.
Example
<?php
Functionsquare($num)
{
Return$num*$num;
}
Echosquare(4);
?>
Internal(built-in)function
Thesearealreadysetinthelibrary.TherealsofunctionthatrequirescertainspecifiedPHP
extensioncompiled.
Example
Tocreateimagefunctionweuseimagecreatetruecolor().
Anonymousfunction
Thisfunctionisalsoknownasclosure,thishasnospecificname.
Example
<?php
Echopreg_replace_callback(‘~-([a-z])~’,function($match[1]);
},‘hello-world’);
?>
SQL
SQLstandsforstandardquerylanguagewhichisusedtoaccessdatabases.Italsousedto
manipulatedatabaseanditisanANSIstandard. MySQListhewidelyusedopensource
Relationaldatabasemanagementsystem.MySQLisgenerallyRDBMSbeingusedfor
developingweb-basedsoftwareapplicationsandyoucanaddSQLqueriestotheMySQL
databasetoinsert,retrieve,updateordeletedata.
LogoofMySQL
History
Itwasdevelopedin1970atIBMwithDonaldD.ChamberlinandRaymondF.
Boyce.
ItwasfirstnamedasSEQUEL.
ThiswassoldtoUSNAVY,C.I.AandU.S.Governmentagenciesafteritspotential
wasrecognized.
UsesofSQL
Usedtoexecutequeryagainstdatabase.
Toretrieveadatafromdatabase.
Toinsertrecord.
Toupdaterecord.
Todeleterecord.
Tocreateanewdatabase.
Tocreatenewtablesindatabase.
Tocreatevariousstorageproceduresindatabase.
Tocreatevariouskindofviewsinadatabase.
Tocreatepermissionsforthefunctioningofvariousproceduresontablesandviews.
HowtouseSQLinwebsite
OneoftheRDMSPROGRAM.
UseofPHPorASP.
UseofSQLforthedatatoberetrieved.
UseHTML/CSS.
MostimportantSQLcommand
Select–Toextractanyneededordesiredrecordordatafromdatabase.
Update–Toupdateormodifyanydatainthedatabase.
Delete–Todeleteorremoveanydatafromdatabase.
Insertinto–Toaddorinsertintodatabase.
Createdatabase–Tocreateorstartanewdatabase.
Alterdatabase–Tomodifyoreditdatabase.
Droptable–Toremoveordeleteatableindatabase.
Createsindex–Tocreateanewindex.
Dropindex-Toremoveordeleteanindex.
SyntaxofSQL
SELECT*FROMCustomers;
SQLisnotcasesensitive.ThismeansbothselectandSELECThavethesamemeaning.
VariouslanguageelementsofSQLlanguages
Clauses
Expression
Predicate
Query
Statement
Insignificantwhitespace
LanguageelementsofSQL
OperatorsinSQL
SQLoperatorsareasfollows.
Operator
Description
Example
=
Equalto
John=‘author’
<>
Notequalto
Dept<>height
>
Greaterthan
100>6
<
Lessthan
6<100
≥
Greaterthanorequal
Rate≥2.6
≤
Lessthanorequal
Rate≤2.6
BETWEEN
Inaninclusiverange
RangeBETWEEN10AND
20
LIKE
Matchthecharacter
NAMELIKE‘WILLY%’
ISORISNOT
Comparetonull
AGEISORISNOTRAJ
IN
Equaltooneofthe
multiplepossible
value
IDIN(100,120,134)
AS
Usedtochangename SelectstudentAS‘section
whenviewingthe
a’
resultortheparticular
value
ISNOT
DISTINCT
FORM
Equaltovaluegiven
orbotharemissing
data
LoanISNOTDISTINCT
FORM-APPLICABLE
Conditions
SQLexpressionCase-Itisoneofthesearchingtechniquesoffindingthematchingcase.Itwasusedin
SQL-92.
Example
CASEWHENN>0
THEN‘POSITIVEVALUE’
WHEN<0
THEN‘NEGATIVEVALUE’
ELSE
‘ZERO’
When-Thisconditionisthesourcethroughwhichthedataiscomparedwiththeoutput
whichissetissimilartoitscondition.Thattimetheactionwhichhastobetakeisdefined
usingwhentheconditionwiththewhenstatementisstated.
Example
CASEa
WHEN1
THEN‘ONEORANGE’
WHEN2
THEN‘TWOORANGES’
ELSE
‘CANNOTCOUNTTHATVALUE’
Then-Thisstatementisusedtoexecuteparticularvalueordisplayparticularvaluewhen
theconditioninWHENstatementissatisfied.
Example
CASEb
WHEN3
THEN‘threeORANGE’
WHEN4
THEN‘fourORANGES’
ELSE
‘CANNOTCOUNTTHATVALUE’.
Else-Whenthewhenconditionisnotsatisfiedtheprocessleadstoanotheroption,thatis
definedaselsestatement.
Example
WHEN5
THEN‘FIVEORANGES’
ELSE
‘CANNOTCOUNTTHATVALUE’.
End-Itisusedtoterminatetheprogramwhichleadsthesystemtostoptheexecution.
Example
CASEx
WHEN1
THEN‘COUNT1’
WHEN2
THEN‘COUNT2’
ELSE‘ERROR’
END
Queries
QueryisthemostcommonlyusedandoneofthekeyoperationsinSQL.
ItisdeclaredusingSELECTstatement.
Itprovidesuserwithvariousmethodstodescribeandshowhis/herdesireddata.
An‘*‘isusedtoshowthatthequeryshouldreturnallcolumnsoftheparticularthat
isqueried.
ItisarequestinformationmethodusedintheSQLthereforeitisakeyfactorand
mostlythebackboneoftheSQL.
MySQLquerywindow
VariousclausesandkeywordsusedinSQLareasfollows.
FROMclause-Thisshowsfromwhereorwhichtabletoretrievedatafrom.
Whereclause-Thisincludesapredicateforcomparisonthishelpsinrestrictingof
therowthatisbeenreturnedbythequery.
Groupbyclause-Usedtoprojectrowsthatareidenticalorhavecommonvalue.
Havingclause-ItisusedinfiltrationofrowwhereitcanbecombinedwithGroup
byclause.
Orderbyclause-Itsortsorarrangesthedatainaformit’sneededtobearranged.
Example
SELECTBooktitleASTIM,
COUNT(*)ASAuthors
FROMBook
JOINBook_TIM
ONBook.isbn=Book_author.isbn
GROUPBYBook.title
Output
Sub-Queries
Thesearenestedqueries.Aquerythatisinanotherqueryandthisisembeddedwithinthe
whereclause.Sub-Queriesareusuallyusedtoreturndatawhichwillbefurtherusedinthe
mainquery.
RulesofSub-queries
Ithastobeenclosedwithinparenthesis.
ItcanhaveonlyonecolumninSELECTclause.
ItisnotallowedtouseODERBYquerywhereasinsteadofthatGROUPBYis
used.
Itcannothaveimmediateenclosureinasetfunction.
Useofsub-queries
Itisusedtojoinonetablewithothertablesoperation.
Thisalsoprovidesfasterremedies.Thisprovidesahierarchicalexecution.
Subquerycanusevaluesfromqueryoutside,thesearecorrelatedsubquery.
Sub-Query
Example
SELECTisbn,
Name,
Price,
FROMBook
WHEREprice<(SELECTAVG(PRICE)FROMBook)
ORDERBYtitle;
3VL
3VLstandsforthree-valuedlogictoSQL.Thereare3fragmentsof3VLwhichareAND,
ORandNOT.Theretableswhicharefollowedin3VL.
p
PANDq
q
True
False
Unknown
True
True
False
Unknown
False
False
False
False
False
Unknown
Unknown Unknown
ANDtable
p
porq
q
True
False
Unknown
True
True
True
True
False
True
False
Unknown
Unknown
True
Unknown
Unknown
ORtable
q
NOTq
True
False
False
True
Unknown
Unknown
Nottable
NULLisoneofthemostfocusedelementofthe3VLandalsohadbeenvery
controversial.Itisjustusedtoindicatethemissingorabsenceofvalueanditdoesnot
belongtoanydatadomain.
Nullrepresentation
ThereforebecauseofitsexistenceissueNULLcannevereverresultineithertrueorfalse
sothirdnewlogicalvalueisintroducedthatis“UNKNOWN”.
Datacontrols
TheDataControlLanguage(DCL)allowsuserstoaccessandmanipulateddata.Itsmain
statementsareasfollow.
GRANTallowsoneormorethanoneusertoperformanoperationonanobject.
REVOKEtoeliminateadefaultgrant.
Example
GRANTSELECT,UPDATE
ONexample
TOsome_user,another_user;
REVOKESELECT,UPDATE
ONexample
FROMsome_user,another_user;
Itcarriesoutfunctionssuchasconnectinsert,select,update,executeanddelete.
Proceduralextensions
ThedesigningofSQLisdoneinaformofquerycontainedrelationdatabase.The
proceduralextensiondiagramofSQLisshownbelow.Thisallowsprogramming
containedinformofroutineswhich.Someelementsknowninproceduralextensionof
SQLareasfollows.
PolymorphismwiththeparametersinSQLofIN,OUTandINOUTmodes.
Variousprocedurescallingstatement.
AtomicBEGINandENDcall.
LocallydeclaredSQLstatement.
Errorsignalingandcursorprocessing.
Declareddatatypes.
Variousconditionalcontrolandloopingstatement.
Proceduralextension
Drawbacks
Portabilitydolackbetweendatabasesystems.
Implementationisnotsupportedwithentirefreedombecauseofthesizeand
complexityoftheSQL.
Thebehavioroftheimplementationatseveralregionsofdatabaseisconfusing
sometimes.
Thereislittlecommercialincentivetovendorstoenforceitasaneasiertaskforthe
usertobringanychangesindatabasesuppliers.
User’sevaluationofdatabasesoftwareavoidsfactorssuchashigherperformances
forthestandardpriority.
Performanceissue
SQLhasalsobeenfoundtohaveaconflictincompatibilitywiththeconsumer’s
priordatabase.
PHPwithMySQL
PHPconnectedtoMySQLfordatamanipulation.Italsoprovidescrossplatform
functionality.
PHPwithMySQL
InawebserveritthereisaPHPinterpreterwhichgetaninputfromthePHPfilespace.
Thisinputisnothing
PHPcreatesaMySQL.Itcanbecreatedbyusing–
MySQLi-MySQLimprovement.
PDO-PHPdataobjects.
Example
MySQLi
<?Php
$servername=“localhost”;
$username=“username”;
$password=“password”;
//Createconnection
$conn=newmysqli($servername,$username,$password);
//Checkconnection
if($conn->connect_error)
{
die(“Connectionfailed:”.$conn->connect_error);
}
//Createdatabase
$sql=“CREATEDATABASEmyDB”;
if($conn->query($sql)===TRUE)
{
echo“Databasecreatedsuccessfully”;
}
else
{
echo“Errorcreatingdatabase:”.$conn->error;
}
$conn->close();
?>
PDO
<?php
$servername=“localhost”;
$username=“username”;
$password=“password”;
try
{
$conn=newPDO(“mysql:host=$servername;dbname=myDB”,$username,$password);
//setthePDOerrormodetoexception
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$sql=“CREATEDATABASEmyDBPDO”;
//useexec()becausenoresultreturned
$conn->exec($sql);
echo“Databasecreated<br>”;
}
catch(PDOException$e)
{
echo$sql.“<br>”.$e->getMessage();
}
$conn=null;
?>
Syntaxrules
QueryhastobequotedinPHP.
Numericvaluemustbeavoided.
NULLvalueshouldnotbequoted,itshouldbeavoided.
Highefficientstatements
Preparationstatement-IsanSQLstatementusetocreateandsendatemplatetothe
particulardatabase.
Executestatement-Isusedtobindalltheretrievedvaluesandtoexecutethem.
CreatingMySQLdatabaseusingPHP
Adminshouldbeprivilegetocreatedatabase.PHPusesmysql_queryforcreationofthe
SQLdatabase.Thishastwoparameterfunctioningwhichistruewhencreationis
successfulandfalsewhenafailureoccurs.
Syntax
Boolmysql_query(sql,connection);
Example
<?php
$dbhost=‘localhost:30306’;
$dbuser=’root’;
$dbpass=‘password’
$conn=mysql_connection($dbhost,$dbuser,$dbpass);
If(!conn)
{
Die(‘couldnotconnect’.mysql_error());
}
Echo‘connectsuccess’;
$sql=‘createdatabasetest-tb’;
$retreval=mysql_query($sql,$conn);
If(!$retval)
{
Die(‘couldnotcreatedatabase‘.mysql_error());
}
Echo“databasetest_dbcreateddatabase\n”;
Mysql_close($conn);
?>
InsertofdatainMySQLdatabaseusingPHP
TheinsertstatementcarriesoutthefunctionusingPHPbyusingquerystatement
mysql_queryfortheSQLINSERTstatement.
Example
<?php
$dbhost=‘localhost:3036’;
$dbuser=‘root’;
$dbpass=‘password’;
$conn=mysql_connect($dbhost,$dbuser,$dbpass);
If(!$conn)
{
Die(‘Couldnotconnect’.mysql_error());
}
$sql=‘INSERTINTOemployee‘.
‘(emp_name,emp_address,emp_salary,join_date)‘.
‘VALUES(“guest”,“XYZ”,2000,NOW())’;
mysql_select_db(‘test_db’);
$retval=mysql_query($sql,$conn);
If(!$retval)
{
Die(‘couldnotenterdata:‘.mysql_error());
}
Echo“Entereddatasuccessfully\n”;
mysql_close($conn);
?>
UpdateinMySQLDatabaseusingPHP
ForupdatinginMySQLthereisaneedofthecommandtobecarriedoutthatisSQL
UPDATEstatementthroughPHPfunctionmysql_query.
Example
<html>
<head>
<title>UpdateaRecordinMySQLDatabase</title>
</head>
<body>
<?php
if(isset($_POST[‘update’]))
{
$dbhost=‘localhost:3036’;
$dbuser=‘root’;
$dbpass=‘password’;
$conn=mysql_connect($dbhost,$dbuser,$dbpass);
If(!$conn)
{
die(‘Couldnotconnect:‘.mysql_error());
}
$emp_id=$_POST[‘emp_id’];
$emp_salary=$_POST[‘emp_salary’];
$sql=“UPDATEemployee“.
“SETemp_salary=$emp_salary“.
“WHEREemp_id=$emp_id”;
mysql_select_db(‘test_db’);
$retval=mysql_query($sql,$conn);
if(!$retval)
{
die(‘Couldnotupdatedata:‘.mysql_error());
}
echo“Updateddatasuccessfully\n”;
mysql_close($conn);
}
else
{
?>
<formmethod=“post”action=”<?php$_PHP_SELF?>”>
<tablewidth=“400”border=“0”cellspacing=“1”cellpadding=“2”>
<tr>
<tdwidth=“100”>EmployeeID</td>
<td><inputname=“emp_id”type=“text”id=“emp_id”></td>
</tr>
<tr>
<tdwidth=“100”>EmployeeSalary</td>
<td><inputname=“emp_salary”type=“text”id=“emp_salary”></td>
</tr>
<tr>
<tdwidth=“100”></td>
<td></td>
</tr>
<tr>
<tdwidth=“100”></td>
<td>
<inputname=“update”type=“submit”id=“update”value=“Update”>
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>
TheupdatingperformedusingPHPinMySQLprovidesmoreefficiencyandexception.
RetrievalinMySQLDatabaseusingPHP
RetrievalinSQListermedasfetchthereforetoperformretrievalinSQLusingPHPa
codeisbeeninusewhichisasfollow
Syntax
Mysql_fetch_arrays()
Example
<?php
$dbhost=‘localhost:3036’;
$dbuser=‘root’;
$dbpass=‘password’;
$conn=mysql_connect($dbhost,$dbuser,$dbpass);
if(!$conn)
{
die(‘Couldnotconnect:‘.mysql_error());
}
$sql=‘SELECTemp_id,emp_name,emp_salaryFROMemployee’;
mysql_select_db(‘test_db’);
$retval=mysql_query($sql,$conn);
if(!$retval)
{
die(‘Couldnotgetdata:‘.mysql_error());
}
while($row=mysql_fetch_array($retval,MYSQL_ASSOC))
{
echo“EMPID:{$row[‘emp_id’]}<br>“.
“EMPNAME:{$row[‘emp_name’]}<br>“.
“EMPSALARY:{$row[‘emp_salary’]}<br>“.
“––––––––––—<br>”;
}
echo“Fetcheddatasuccessfully\n”;
mysql_close($conn);
?>
DeletingofMySQLDatabaseusingPHP
Thedatabaseonceisnotneededandtheuserdon’twanttohaveitanymoreorwantto
freespacethentheusercanpassastatementthatwouldstatetodeletethedatabase
throughthemysql_queryfordeletionofdata.ThetermusedinSQLfordeleteisdrop.
Example
<?php
$dbhost=‘localhost:3036’;
$dbuser=‘root’;
$dbpass=‘password’;
$conn=mysql_connect($dBBhost,$dBBuser,$dBBpass);
if(!$conn)
{
Die(‘couldnotconnect:‘.mysql_error());
}
$sql=‘DROPDATABASEtest_d’;
$retval=mysql_query($sql,$conn);
If(!$retval)
{
Die(‘Couldnotdeletedatabasedb_test‘mysql_error());
}
Echo“Databasedeletedsuccessfully\n”;
mysql_close($conn);
?>
DeletingofdatafromMySQLusingPHP
WhenintendedortheuserwantstodeleteanydatafromtheMySQLdatabaseusingPHP
theusercanpassastatementstatingthatthroughmysql_query.
Example
<html>
<head>
<title>DeletefromMySQLDatabase</title>
</head>
<body>
<?php
if(isset($_POST[‘delete’]))
{
$dBBhost=‘localhost:3036’;
$dBBuser=‘root’;
$dBBpass=‘password’;
$conn=mysql_connect($dBBhost,$dBBuser,$dBbpass);
if(!$conn)
{
Die(‘couldnotconnect:‘.mysql_error());
}
$emp_id=$_POST[‘emp_id’];
$sql=“DELETEemployee“.
“WHEREemp_id=$emp_id”;
mysql_select_db(‘test_d’);
$retval=mysql_query($sql,$conn);
if(!$retval)
{
Die(‘couldnotdeletedata:‘.mysql_error());
}
Echo“Deletionsuccessful\n”;
mysql_close($conn);
}
else
{
?>
<formmethod=“post”action=”<?php$_PHP_SELF?>”>
<tablewidth=“400”border=“0”cellspacing=“1”cellpadding=“2”>
<tr>
<tdwidth=“100”>EmployeeID</td>
<td><inputEPRORNAME=“ePROR_NAMED”type=“textT”id=“ePROR_idD”></td>
</tr>
<tr>
<tdwidth=“100”></td>
<td></td>
</tr>
<tr>
<tdwidth=“100”></td>
<td>
<inputEPROR=“delete”type=“submit”id=“delete”value=“Delete”>
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>
YoucantakebackupoftheSQLdatabaseusingfollowingmethods.
UsingcommandofSQLthroughPHP.
UsingmysqldumpwiththehelpofPHP.
ByusingaphpMyAdminuserinterface.
Knowledgeflow:moreeBooksandApps
GetmoreGooglePlayBooks
GetmoreeBooks
GetmoreappsfromGooglePlaystore
GetmoreappsfromAmazonappstore