You are on page 1of 53

OOPSInterviewQuestions

1)ExplaintherationalebehindObjectOrientedconcepts?
Objectorientedconceptsformthebaseofallmodernprogramminglanguages.Understandingthebas
icconceptsofobject-
orientationhelpsadevelopertousevariousmoderndayprogramminglanguages,moreeffectively.
2)ExplainaboutObjectorientedprogramming?
Objectorientedprogrammingisoneofthemostpopularmethodologiesinsoftwaredevelopment.Itof
fersapowerfulmodelforcreatingcomputerprograms.Itspeedstheprogramdevelopmentprocess,im
provesmaintenanceandenhancesreusabilityofprograms.
3)Explainwhatisanobject?
Anobjectisacombinationofmessagesanddata.Objectscanreceiveandsendmessagesandusemessa
gestointeractwitheachother.Themessagescontaininformationthatistobepassedtotherecipientobj
ect.
4)ExplaintheimplementationphasewithrespecttoOOP?
ThedesignphaseisfollowedbyOOP,whichistheimplementationphase.OOPprovidesspecification
sforwritingprogramsinaprogramminglanguage.Duringtheimplementationphase,programmingi
sdoneaspertherequirementsgatheredduringtheanalysisanddesignphases.
5)ExplainabouttheDesignPhase?
Inthedesignphase,thedevelopersofthesystemdocumenttheirunderstandingofthesystem.Designg
eneratestheblueprintofthesystemthatistobeimplemented.Thefirststepincreatinganobjectoriente
ddesignistheidentificationofclassesandtheirrelationships.
6)Explainaboutaclass?
Classdescribesthenatureofaparticularthing.StructureandmodularityisprovidedbyaClassinobject
orientedprogrammingenvironment.Characteristicsoftheclassshouldbeunderstandablebyanordi
narynonprogrammeranditshouldalsoconveythemeaningoftheproblemstatementtohim.Classacts
likeablueprint.

7)Explainaboutinstanceinobjectorientedprogramming?
Everyclassandanobjecthaveaninstance.Instanceofaparticularobjectiscreatedatruntime.Valuesd
efinedforaparticularobjectdefineitsState.Instanceofanobjectexplainstherelationshipbetweendif
ferentelements.
8)Explainaboutinheritance?
Inheritancerevolvesaroundtheconceptofinheritingknowledgeandclassattributesfromtheparentcl
ass.Ingeneralsenseasubclasstriestoacquirecharacteristicsfromaparentclassandtheycanalsohavet
heirowncharacteristics.Inheritanceformsanimportantconceptinobjectorientedprogramming.
9)Explainaboutmultipleinheritance?
Inheritanceinvolvesinheritingcharacteristicsfromitsparentsalsotheycanhavetheirowncharacteri
stics.Inmultipleinheritanceaclasscanhavecharacteristicsfrommultipleparentsorclasses.Asubcla
sscanhavecharacteristicsfrommultipleparentsandstillcanhaveitsowncharacteristics.
10)Explainaboutencapsulation?
Encapsulationpassesthemessagewithoutrevealingtheexactfunctionaldetailsoftheclass.Itallowso
nlytherelevantinformationtotheuserwithoutrevealingthefunctionalmechanismthroughwhichap
articularclasshadfunctioned.
11)Explainaboutabstraction?
Abstractionsimplifiesacomplexproblemtoasimplerproblembyspecifyingandmodelingtheclasst
otherelevantproblemscenario.Itsimplifiestheproblembygivingtheclassitsspecificclassofinherita
nce.Compositionalsohelpsinsolvingtheproblemtoanextent.
12)Explainthemechanismofcomposition?
Compositionhelpstosimplifyacomplexproblemintoaneasierproblem.Itmakesdifferentclassesan
dobjectstointeractwitheachotherthusmakingtheproblemtobesolvedautomatically.Itinteractswit
htheproblembymakingdifferentclassesandobjectstosendamessagetoeachother.
13)Explainaboutpolymorphism?
Polymorphismhelpsasubclasstobehavelikeaparentclass.Whenanobjectbelongingtodifferentdat
atypesrespondtomethodswhichhaveasamename,theonlyconditionbeingthatthosemethodsshoul
dperformdifferentfunction.
14)Explainaboutoverridingpolymorphism?
Overridingpolymorphismisknowntooccurwhenadatatypecanperformdifferentfunctions.Forexa
mpleanadditionoperatorcanperformdifferentfunctionssuchasaddition,floatadditionetc.Overridi
ngpolymorphismisgenerallyusedincomplexprojectswheretheuseofaparameterismore.
15)Explainaboutobjectorienteddatabases?
Objectorienteddatabasesareverypopularsuchasrelationaldatabasemanagementsystems.Objecto
rienteddatabasessystemsusespecificstructurethroughwhichtheyextractdataandtheycombinethe
dataforaspecificoutput.TheseDBMSuseobjectorientedlanguagestomaketheprocesseasier.
16)Explainaboutparametricpolymorphism?
Parametricpolymorphismissupportedbymanyobjectorientedlanguagesandtheyareveryimportan
tforobjectorientedtechniques.Inparametricpolymorphismcodeiswrittenwithoutanyspecificatio
nforthetypeofdatapresent.Henceitcanbeusedanynumberoftimes.
17)WhatareallthelanguageswhichsupportOOP?
ThereareseveralprogramminglanguageswhichareimplementingOOPbecauseofitscloseproximit
ytosolvereallifeproblems.LanguagessuchasPython,Ruby,Rubyonrails,Perl,PHP,Coldfusion,et
cuseOOP.StillmanylanguagesprefertouseDOMbasedlanguagesduetotheeaseincoding.

---------

1)Explainwhatisobjectorientedprogramminglanguage?
Objectorientedprogramminglanguageallowsconceptssuchasmodularity,encapsulation,polymor
phismandinheritance.Simulaiscreditedtobethefirstobjectorientedlanguage.Objectsaresaidtobet
hemostimportantpartofobjectorientedlanguage.Conceptrevolvesaroundmakingsimulationprog
ramsaroundanobject.
2)Namesomelanguageswhichhaveobjectorientedlanguageandcharacteristics?
SomeofthelanguageswhichhaveobjectorientedlanguagespresentinthemareABAP,ECMAScript
,C+
+,Perl,LISP,C#,Tcl,VB,Ruby,Python,PHP,etc.Popularityoftheselanguageshasincreasedconsid
erablyastheycansolvecomplexproblemswithease.
3)ExplainaboutUML?
UMLorunifiedmodelinglanguageisregardedtoimplementcompletespecificationsandfeaturesofo
bjectorientedlanguage.Abstractdesigncanbeimplementedinobjectorientedprogramminglangua
ges.ItlacksimplementationofpolymorphismonmessageargumentswhichisaOOPsfeature.
4)Explainthemeaningofobjectinobjectorientedprogramming?
Languageswhicharecalledasobjectorientedalmostimplementeverythinginthemasobjectssuchas
punctuations,characters,prototypes,classes,modules,blocks,etc.Theyweredesignedtofacilitatea
ndimplementobjectorientedmethods.
5)Explainaboutmessagepassinginobjectorientedprogramming?
Messagepassingisamethodbywhichanobjectsendsdatatoanotherobjectorrequestsotherobjecttoi
nvokemethod.Thisisalsoknownasinterfacing.Itactslikeamessengerfromoneobjecttootherobjectt
oconveyspecificinstructions.
6)StateaboutJavaanditsrelationtoObjectorientedprogramming?
Javaiswidelyusedanditsshareisincreasingconsiderablywhichispartlyduetoitscloseresemblancet
oobjectorientedlanguagessuchasCandC+
+.CodewritteninJavacanbetransportedtomanydifferentplatformswithoutchangingit.Itimplemen
tsvirtualmachine.
7)Whataretheproblemsfacedbythedeveloperusingobjectorientedprogramminglanguage?
Thesearesomeoftheproblemsfacedbythedeveloperusingobjectorientedlanguagetheyare:-
1)Objectorientedusesdesignpatternswhichcanbereferredtoasanythingingeneral.
2)Repeatablesolutiontoaproblemcancauseconcernanddisagreementsanditisoneofthemajorprobl
emsinsoftwaredesign.
8)Statesomeoftheadvantagesofobjectorientedprogramming?
Someoftheadvantagesofobjectorientedprogrammingareasfollows:-
1)Aclearmodularstructurecanbeobtainedwhichcanbeusedasaprototypeanditwillnotrevealtheme
chanismbehindthedesign.Itdoeshaveaclearinterface.
2)Easeofmaintenanceandmodificationtotheexistingobjectscanbedonewithease.
3)AgoodframeworkisprovidedwhichfacilitatesincreatingrichGUIapplications.
9)ExplainaboutinheritanceinOOPS?
Objectsinoneclasscanacquirepropertiesoftheobjectsinotherclassesbywayofinheritance.Reusabi
litywhichisamajorfactorisprovidedinobjectorientedprogrammingwhichaddsfeaturestoaclasswit
houtmodifyingit.Newclasscanbeobtainedfromaclasswhichisalreadypresent.
10)Explainabouttherelationshipbetweenobjectorientedprogramminganddatabases?
Objectorientedprogrammingandrelationaldatabaseprogrammingarealmostsimilarinsoftwareen
gineering.RDBMSwillnotstoreobjectsdirectlyandthat’swhereobjectorientedprogrammingcom
esintoplay.Objectrelationalmappingisonesuchsolution.
11)ExplainaboutaclassinOOP?
InObjectorientedprogrammingusageofclassoftenoccurs.Aclassdefinesthecharacteristicsofanob
jectanditsbehaviors.Thisdefinesthenatureandfunctioningofaspecifiedobjecttowhichitisassigne
d.Codeforaclassshouldbeencapsulated.

12)Explaintheusageofencapsulation?
Encapsulationspecifiesthedifferentclasseswhichcanusethemembersofanobject.Themaingoalof
encapsulationistoprovideaninterfacetoclientswhichdecreasethedependencyonthosefeaturesand
partswhicharelikelytochangeinfuture.Thisfacilitateseasychangestothecodeandfeatures.
13)Explainaboutabstraction?
Abstractioncanalsobeachievedthroughcomposition.Itsolvesacomplexproblembydefiningonlyt
hoseclasseswhicharerelevanttotheproblemandnotinvolvingthewholecomplexcodeintoplay.
14)Explainwhatamethodis?
Amethodwillaffectonlyaparticularobjecttowhichitisspecified.Methodsareverbsmeaningtheyde
fineactionswhichaparticularobjectwillperform.Italsodefinesvariousothercharacteristicsofaparti
cularobject.
15)NamethedifferentCreationalpatternsinOOdesign?
TherearethreepatternsofdesignoutofwhichCreationalpatternsplayanimportantrolethevariouspat
ternsdescribedunderneaththisare:-
1)Factorypattern
2)Singletonpattern
3)Prototypepattern
4)Abstractfactorypattern
5)Builderpattern
16)Explainaboutrealisticmodeling?
Asweliveinaworldofobjects,itlogicallyfollowsthattheobjectorientedapproachmodelstherealwor
ldaccurately.Theobjectorientedapproachallowsyoutoidentifyentitiesasobjectshavingattributesa
ndbehavior.
17)Explainabouttheanalysisphase?
Theanlaysisortheobjectorientedanalysisphaseconsidersthesystemasasolutiontoaprobleminitsen
vironmentordomain.Developerconcentratesonobtainingasmuchinformationaspossibleaboutthe
problem.Criticalrequirementsneedstobeidentified.

PHPOOPSInterviewQuestions&Answers
August13,2008—sharag

PHPOOPSInterviewQuestions&Answers
1)Explainwhatisobjectorientedprogramminglanguage?
Objectorientedprogramminglanguageallowsconceptssuchasmodularity,encapsulation,polymor
phismandinheritance.Objectsaresaidtobethemostimportantpartofobjectorientedlanguage.Conc
eptrevolvesaroundmakingsimulationprogramsaroundanobject.Organizeaprogramarounditsdat
a(object)&setwelldefineinterfacetothatdata.i.e.objectsandasetofwelldefinedinterfacestothatdat
a.OOPisthecommonabbreviationforObject-
OrientedProgramming.OOpshavemanypropertiessuchasDataHiding,Inheritence,DataAbsracti
on,DataEncapsulationandmanymore.

2)Namesomelanguageswhichhaveobjectorientedlanguageandcharacteristics?
SomeofthelanguageswhichhaveobjectorientedlanguagespresentinthemareABAP,ECMAScript
,C+
+,Perl,LISP,C#,Tcl,VB,Ruby,Python,PHP,etc.Popularityoftheselanguageshasincreasedconsid
erablyastheycansolvecomplexproblemswithease.
3)ExplainaboutUML?
UMLorunifiedmodelinglanguageisregardedtoimplementcompletespecificationsandfeaturesofo
bjectorientedlanguage.Abstractdesigncanbeimplementedinobjectorientedprogramminglangua
ges.ItlacksimplementationofpolymorphismonmessageargumentswhichisaOOPsfeature.
4)Explainthemeaningofobjectinobjectorientedprogramming?
Languageswhicharecalledasobjectorientedalmostimplementeverythinginthemasobjectssuchas
punctuations,characters,prototypes,classes,modules,blocks,etc.Theyweredesignedtofacilitatea
ndimplementobjectorientedmethods.
5)Explainaboutmessagepassinginobjectorientedprogramming?
Messagepassingisamethodbywhichanobjectsendsdatatoanotherobjectorrequestsotherobjecttoi
nvokemethod.Thisisalsoknownasinterfacing.Itactslikeamessengerfromoneobjecttootherobjectt
oconveyspecificinstructions.
6)StateaboutJavaanditsrelationtoObjectorientedprogramming?
Javaiswidelyusedanditsshareisincreasingconsiderablywhichispartlyduetoitscloseresemblancet
oobjectorientedlanguagessuchasC+
+.CodewritteninJavacanbetransportedtomanydifferentplatformswithoutchangingit.Itimplemen
tsvirtualmachine.
7)Whataretheproblemsfacedbythedeveloperusingobjectorientedprogramminglanguage?

Thesearesomeoftheproblemsfacedbythedeveloperusingobjectorientedlanguagetheyare:-

a)Objectorientedusesdesignpatternswhichcanbereferredtoasanythingingeneral.
b)Repeatablesolutiontoaproblemcancauseconcernanddisagreementsanditisoneofthemajorprobl
emsinsoftwaredesign.
8)Statesomeoftheadvantagesofobjectorientedprogramming?
Someoftheadvantagesofobjectorientedprogrammingareasfollows:-
a)Aclearmodularstructurecanbeobtainedwhichcanbeusedasaprototypeanditwillnotrevealtheme
chanismbehindthedesign.Itdoeshaveaclearinterface.
b)Easeofmaintenanceandmodificationtotheexistingobjectscanbedonewithease.
c)AgoodframeworkisprovidedwhichfacilitatesincreatingrichGUIapplications.
9)ExplainaboutinheritanceinOOPS?
Objectsinoneclasscanacquirepropertiesoftheobjectsinotherclassesbywayofinheritance.Reusabi
litywhichisamajorfactorisprovidedinobjectorientedprogrammingwhichaddsfeaturestoaclasswit
houtmodifyingit.Newclasscanbeobtainedfromaclasswhichisalreadypresent.
10)Explainabouttherelationshipbetweenobjectorientedprogramminganddatabases?
Objectorientedprogrammingandrelationaldatabaseprogrammingarealmostsimilarinsoftwareen
gineering.RDBMSwillnotstoreobjectsdirectlyandthat’swhereobjectorientedprogrammingcom
esintoplay.Objectrelationalmappingisonesuchsolution.
11)ExplainaboutaclassinOOP?
InObjectorientedprogrammingusageofclassoftenoccurs.Aclassdefinesthecharacteristicsofanob
jectanditsbehaviors.Thisdefinesthenatureandfunctioningofaspecifiedobjecttowhichitisassigne
d.Codeforaclassshouldbeencapsulated.

12)Explaintheusageofencapsulation?
Encapsulationspecifiesthedifferentclasseswhichcanusethemembersofanobject.Themaingoalof
encapsulationistoprovideaninterfacetoclientswhichdecreasethedependencyonthosefeaturesand
partswhicharelikelytochangeinfuture.Thisfacilitateseasychangestothecodeandfeatures.
13)Explainaboutabstraction?
Abstractioncanalsobeachievedthroughcomposition.Itsolvesacomplexproblembydefiningonlyt
hoseclasseswhicharerelevanttotheproblemandnotinvolvingthewholecomplexcodeintoplay.
14)Explainwhatamethodis?
Amethodwillaffectonlyaparticularobjecttowhichitisspecified.Methodsareverbsmeaningtheyde
fineactionswhichaparticularobjectwillperform.Italsodefinesvariousothercharacteristicsofaparti
cularobject.
15)NamethedifferentCreationalpatternsinOOdesign?
TherearethreepatternsofdesignoutofwhichCreationalpatternsplayanimportantrolethevariouspat
ternsdescribedunderneaththisare:-
a)Factorypattern
b)Singletonpattern
c)Prototypepattern
d)Abstractfactorypattern
e)Builderpattern
16)Explainaboutrealisticmodeling?
Asweliveinaworldofobjects,itlogicallyfollowsthattheobjectorientedapproachmodelstherealwor
ldaccurately.Theobjectorientedapproachallowsyoutoidentifyentitiesasobjectshavingattributesa
ndbehavior.
17)Explainabouttheanalysisphase?
Theanlaysisortheobjectorientedanalysisphaseconsidersthesystemasasolutiontoaprobleminitsen
vironmentordomain.Developerconcentratesonobtainingasmuchinformationaspossibleaboutthe
problem.Criticalrequirementsneedstobeidentified.

***************************************************************************
*********************************

1)ExplaintherationalebehindObjectOrientedconcepts?

Objectorientedconceptsformthebaseofallmodernprogramminglanguages.Understandingthebas
icconceptsofobject-
orientationhelpsadevelopertousevariousmoderndayprogramminglanguages,moreeffectively.
2)ExplainaboutObjectorientedprogramming?
Objectorientedprogrammingisoneofthemostpopularmethodologiesinsoftwaredevelopment.Itof
fersapowerfulmodelforcreatingcomputerprograms.Itspeedstheprogramdevelopmentprocess,im
provesmaintenanceandenhancesreusabilityofprograms.
3)Explainwhatisanobject?
Anobjectisacombinationofmessagesanddata.Objectscanreceiveandsendmessagesandusemessa
gestointeractwitheachother.Themessagescontaininformationthatistobepassedtotherecipientobj
ect.
4)ExplaintheimplementationphasewithrespecttoOOP?
ThedesignphaseisfollowedbyOOP,whichistheimplementationphase.OOPprovidesspecification
sforwritingprogramsinaprogramminglanguage.Duringtheimplementationphase,programmingi
sdoneaspertherequirementsgatheredduringtheanalysisanddesignphases.
5)ExplainabouttheDesignPhase?
Inthedesignphase,thedevelopersofthesystemdocumenttheirunderstandingofthesystem.Designg
eneratestheblueprintofthesystemthatistobeimplemented.Thefirststepincreatinganobjectoriente
ddesignistheidentificationofclassesandtheirrelationships.
6)Explainaboutaclass?
Classdescribesthenatureofaparticularthing.StructureandmodularityisprovidedbyaClassinobject
orientedprogrammingenvironment.Characteristicsoftheclassshouldbeunderstandablebyanordi
narynonprogrammeranditshouldalsoconveythemeaningoftheproblemstatementtohim.Classacts
likeablueprint.

7)Explainaboutinstanceinobjectorientedprogramming?
Everyclassandanobjecthaveaninstance.Instanceofaparticularobjectiscreatedatruntime.Valuesd
efinedforaparticularobjectdefineitsState.Instanceofanobjectexplainstherelationshipbetweendif
ferentelements.
8)Explainaboutinheritance?
Inheritancerevolvesaroundtheconceptofinheritingknowledgeandclassattributesfromtheparentcl
ass.Ingeneralsenseasubclasstriestoacquirecharacteristicsfromaparentclassandtheycanalsohavet
heirowncharacteristics.Inheritanceformsanimportantconceptinobjectorientedprogramming.
9)Explainaboutmultipleinheritance?
Inheritanceinvolvesinheritingcharacteristicsfromitsparentsalsotheycanhavetheirowncharacteri
stics.Inmultipleinheritanceaclasscanhavecharacteristicsfrommultipleparentsorclasses.Asubcla
sscanhavecharacteristicsfrommultipleparentsandstillcanhaveitsowncharacteristics.
10)Explainaboutencapsulation?
Encapsulationpassesthemessagewithoutrevealingtheexactfunctionaldetailsoftheclass.Itallowso
nlytherelevantinformationtotheuserwithoutrevealingthefunctionalmechanismthroughwhichap
articularclasshadfunctioned.
11)Explainaboutabstraction?
Abstractionsimplifiesacomplexproblemtoasimplerproblembyspecifyingandmodelingtheclasst
otherelevantproblemscenario.Itsimplifiestheproblembygivingtheclassitsspecificclassofinherita
nce.Compositionalsohelpsinsolvingtheproblemtoanextent.
12)Explainthemechanismofcomposition?
Compositionhelpstosimplifyacomplexproblemintoaneasierproblem.Itmakesdifferentclassesan
dobjectstointeractwitheachotherthusmakingtheproblemtobesolvedautomatically.Itinteractswit
htheproblembymakingdifferentclassesandobjectstosendamessagetoeachother.
13)Explainaboutpolymorphism?
Polymorphismhelpsasubclasstobehavelikeaparentclass.Whenanobjectbelongingtodifferentdat
atypesrespondtomethodswhichhaveasamename,theonlyconditionbeingthatthosemethodsshoul
dperformdifferentfunction.
14)Explainaboutoverridingpolymorphism?
Overridingpolymorphismisknowntooccurwhenadatatypecanperformdifferentfunctions.Forexa
mpleanadditionoperatorcanperformdifferentfunctionssuchasaddition,floatadditionetc.Overridi
ngpolymorphismisgenerallyusedincomplexprojectswheretheuseofaparameterismore.
15)Explainaboutobjectorienteddatabases?
Objectorienteddatabasesareverypopularsuchasrelationaldatabasemanagementsystems.Objecto
rienteddatabasessystemsusespecificstructurethroughwhichtheyextractdataandtheycombinethe
dataforaspecificoutput.TheseDBMSuseobjectorientedlanguagestomaketheprocesseasier.
16)Explainaboutparametricpolymorphism?
Parametricpolymorphismissupportedbymanyobjectorientedlanguagesandtheyareveryimportan
tforobjectorientedtechniques.Inparametricpolymorphismcodeiswrittenwithoutanyspecificatio
nforthetypeofdatapresent.Henceitcanbeusedanynumberoftimes.
17)WhatareallthelanguageswhichsupportOOP?
ThereareseveralprogramminglanguageswhichareimplementingOOPbecauseofitscloseproximit
ytosolvereallifeproblems.LanguagessuchasPython,Ruby,Rubyonrails,Perl,PHP,Coldfusion,et
cuseOOP.StillmanylanguagesprefertouseDOMbasedlanguagesduetotheeaseincoding.

vargaJsHost=((“https:”==document.location.protocol)?“https://ssl.”:“http://www.”);
document.write(unescape(“%3Cscriptsrc=’”+gaJsHost+“google-
analytics.com/ga.js’type=’text/javascript’%3E%3C/script%3E”));

try{
varpageTracker=_gat._getTracker(“UA-1855756-5″);
pageTracker._trackPageview();
}catch(err){}

Howicanmakeachatpageinphpinsimple
Differencebetweenmysql_connectandmysql_pconnect.
Whatistheuseofobj_start()?
whatisdifferencebetweenmysql_fetch_array(),mysql_fetch_row()andmysql_fetch_object()pleaseinsertwithexample.
Whatisdifferencebetweenrequire_once(),require(),include().Becouseabovethreefunctionuselyusetocallafileinanotherfile
.
HowtopreventformhijackinginPHP?
WhatisthedifferencebetweenSplitandExplode
Whatisthedifferencebetweenechoandprintstatement?
HowcanImaintainthecountofhowmanypersonshavehitmysite?
Howtohandledropdownboxchangeeventwithoutrefreshingpage?
WhatarenewfeaturesthatareinaddedinPHP5?
WhichwillexecutefasteronphpPOSTorGET?Explain
Iamtryingtoassignavariablethevalueof0123,butitkeepscomingupwithadifferentnumber,what?stheproblem?
What'sPHP?
WheredoesthePHPsessionstored,eitherclientsideorserverside?
HowToWritetheFORMTagCorrectlyforUploadingFiles?
Howcanwesubmitaformwithoutasubmitbutton?
Whatarethedifferencesbetweenrequireandinclude,include_once?
Howdoweknowbrowserproperties?
Whatisthedifferencebetween$messageand$$message?

What do you need to do to improve the performance (speedy execution) for the script you have written?
How do you capture audio/video in PHP?
How do you pass a variable by value?
How do you create subdomains using PHP?
what would be the differences between PHP and Java?
What is the use of header() function in php?
Name and explain five of the PHP error constants?
What is the use of sprintf() function?
How can I execute a PHP script using command line?
What are the valid values for xlink:actuate and xlink:show?
What is the difference between session_register and $_session?
Explain about PHP cookies?
How can I maintain the count of how many persons have hit my site?
What is meant by urlencode and urldecode?
If you have to work with dates in the following format: "Tuesday, February 14, 2006 @ 10:39 am", how can you
convert them to another format, that is easier to use?
What are the different tables present in MySQL? Which type of table is generated when we are creating a table in the
following syntax: create table employee(eno int(2),ename varchar(10))?
How To Create a Table?
What are the different filter functions used to filter a variable?
difference between require() and include()
In case of download in php, How will you make a percentage bar showing current status of total 100%?
Explain about the $_GET variable of PHP?
What does a special set of tags do in PHP?
How would you initialize your strings with single quotes or double quotes?
How do download in php ?
How can i get ip address?
What is meant by PEAR in php?
What Is a Persistent Cookie?
Can I resolve the URI used as an XML namespace name?
What does the URI used as an XML namespace name point to?
What is a PHP accelerator?
Explain about looping in PHP?
Explain about require and include function?
Define about declare construct?
What is the alternative structure for control structures?
Explain about switch statement in PHP?
Explain about PHP filter and why it should be used?
What exactly is validating and sanitizing?
What is the effect of large number of data stored in a database on a website ?
Describe about PHP error and logging information?
Explain about Functions in PHP?
How can we know the number of days between two given dates using PHP?
what is difference between mysql_connect and mysql_pconnect
How to add multiple categories through PHP?
How i will check that user is, logged in or not. i want to make it a function and i want to use in each page and after
login i want to go in current page(same page. where i was working)
What Is a Session?
How can we repair a MySQL table?
How do you define a constant?
How To Get the Uploaded File Information in the Receiving Script?
What is the difference between mysql_fetch_object and mysql_fetch_array?
Would I use print "$a dollars" or "{$a} dollars" to print out the amount of dollars in this example?
what is a cookie , explaing by code ?
What exactly is PHP ?
Explain about the data types in PHP?
Explain about objects in PHP?
What is htaccess?
How to get the URL domain name in PHP?
What is the diffrence between Notify URL and Return URL?
Is Inheritance supported in PHP?

How can we submit a form without a submit button?


We can use a simple JavaScript code linked to an event trigger of any form field. In the
JavaScript code, we can call the document.form.submit() function to submit the form ....!
What is meant by urlencode and urldecode?
string urlencode(str) where str contains a string like this “hello world” and the return value
will be URL encoded and can be use to append with URLs, normaly used to appned data for
GET like someurl.com?var=hello%world string urldocode(str) this will simple decode the
GET variable’s valueLike it echo (urldecode($_GET_VARS[var])) will output “Hello world”
....!
Which function in PHP gives us absolute path of a file on the server?
<?php $p = getcwd(); echo $p; ?> Ans: getcwd() Here I have stored my files under httdocs
(using php5,i haven't checked under php4) so I get the output as C:\apache2triad\htdocs you
may get your path information while runnings the above code. :)  
what is the output below mentioned?
<?php $findme = 'a'; $mystring2 = 'ABC'; $pos1 = stripos($mystring2, $findme); if ($pos1
=== false) { echo "string is not matched"; } else {echo ‘ match found’;} ?> a) String not
matched b) Match found c) All of the above d) None of the above ANS : b (note stripos)
What is meant by Exceptional Handling?
Exceptions PHP 5 has an exception model similar to that of other programming languages.
An exception can be thrown, try and caught within PHP. A Try block must include at least
one catch block. Multiple catch blocks can be used to catch different classtypes; execution
will continue after that last catch block defined in sequence. Exceptions can be thrown within
catch blocks. When an exception is thrown, code following the statement will not be executed
and PHP will attempt to find the first matching catch block. ....!
PHP Functions for WDDX
PHP has a few other functions that can be useful when you're working with WDDX: <?php
$names = array("Andrew", "Emma"); $name2 = "Terry"; $name3 = "Mary"; $name4 =
"Thomas"; $wddxpack = wddx_packet_start("PHP-WDDX"); wddx_add_vars($wddxpack,
"names"); wddx_add_vars($wddxpack, "name2"); wddx_add_vars($wddxpack, "name3");
wddx_add_vars($wdd....!
Should I use an HTTP GET or POST for my AJAX calls?
AJAX requests should use an HTTP GET request when retrieving data where the data will
not change for a given request URL. An HTTP POST should be used when state is updated
on the server. This is in line with HTTP idem potency recommendations and is highly
recommended for a consistent web application architecture. ....!
What are the commands to find the structure of a MySQL table other than EXPLAIN
command?
describe table_name ....!
What is the functionality of md5 function in PHP?
Calculate the md5 hash of a string. The hash is a 32-character hexadecimal number. ....!
How can we repair a MySQL table?
The syntex for repairing a mysql table is REPAIR TABLENAME, [TABLENAME, ],
[Quick],[Extended] This command will repair the table specified if the quick is given the
mysql will do a repair of only the index tree if the extended is given it will create index row
by row ....!
What is meant by Session Clustering?
The Session Manager session support allows multiple server instances to share a common
pool of sessions, known as a session cluster Session clustering setting up methods : #1)First
methods, is to have a NFS shared where session will be store. Setting this is quite easy, just a
little modification on php.ini file to change the “session.save_path ? directive to point to the
NFS share. The main problem with NFS is on high traffic, NFS share is really slow. So
synchronisation and data corruption can arrive and ....!
Your first PHP script - "Hello World"
<?php echo 'Hello World'; ?> ....!
How can we take a backup of mysql table and restore it?
These are the simplest method to backup and restore the MySQl table For taking the bakup of
all the databases mysqldump --user {user} --password {password} -A > {file name to dump}
To take the backup of a specific database mysqldump --user {user} --password {password}
dbname > {filename to dump} To restore a SQL dump please use this mysql --user {user}
--password {password} dbName < {filename to restore}
What is Phishing?
In computing, phishing is a form of criminal activity using social engineering techniques. It is
characterized by attempts to fraudulently acquire sensitive information, such as passwords
and credit card details, by masquerading as a trustworthy person or business in an apparently
official electronic communication. Phishing is typically carried out using email or an instant
message. The term phishing derives from password harvesting and the use of increasingly
sophisticated lures to "fish" for users' financial information and passwords.
How can we encrypt and decrypt a data present in a MySQL table using MySQL?
There are two methods AES_ENCRYPT () and AES_DECRYPT () ....!
There are two methods

AES_ENCRYPT () and AES_DECRYPT ()

....!

1. What is MySQL?
2. Should I use an HTTP GET or POST for my AJAX calls?
3. What API function provides the connection between the client and server?
4. what is ajax? when ajax was born?

What function would you use to redirect the browser to a new page?
1. redir() 2. header() 3. location() 4. redirect() ANS:header() ....!
what is Memcache?
Memcache is a technology which caches objects in memory where your web application can
get to them really fast. It is used by sites such as Digg.com, Facebook.com and
NowPublic.com and is widely recognized as an essential ingredient in scaling any LAMP
application to handle enormous traffic.   ....!
What is the difference between CHAR and VARCHAR data types?
Ans: CHAR is a fixed length data type. CHAR(n) will take n characters of storage even if
you enter less than n characters to that column. For example, "answers" will be stored as
"answers " in CHAR(10) column. VARCHAR is a variable length data type. VARCHAR(n)
will take only the required storage for the actual number of characters entered to that column.
For example, "answers" will be stored as "answers&q....!
List out some session functions in php?
session_save_path -- Get and/or set the current session save path session_is_registered -- Find
out whether a global variable is registered in a session session_unset -- Free all session
variables session_cache_expire -- Return current cache expire session_cache_limiter -- Get
and/or set the current cache limiter session_commit -- Alias of session_write_close()
session_decode -- Decodes session data from a string session_destroy -- Destroys all data
registered to a sessi....!
what is the output here?
<?php $x = 'Sunil'; echo ‘Hello $x’; ?> a. hello sunil b. Parse error c. hello $x d. syntax error
ANS: c published by www.w3answers.com ....!
how to opening excel files in windows nad linux using php ?
if you're using PHP on Windows, you can use the inbuilt COM library $excel = new
COM("excel.application"); $excel->Workbooks->Open("filename.xls"); On Linux machines,
is PHPExcelReader( download from sourceforgr.net), and it seems to work very efficiently
and easily with only a few lines of code. $data = new Spreadsheet_Excel_Reader(); $data-
>read("filename.xls"); And you can access the data with a simple loop:
How can we know the count/number of elements of an array?
a) sizeof($urarray) This function is an alias of count()b) count($urarray) ....!
what is the output of 2^2 in php ?
The answer is 0 (Zero) Important note Everyone expected answer would be 4.But answer is
zero.How it happened only in php ? The ^ operator is different in each language.In PHP ^
means the bitwise exlusive or of the two numbers. www.w3answers.com ....!
How can we know the number of days between two given dates using MySQL?
Using DATEDIFF() SELECT DATEDIFF(NOW(),'2007-07-15'); ....!
What is meant by Session Clustering?
The Session Manager session support allows multiple server instances to share a common
pool of sessions, known as a session cluster Session clustering setting up methods : #1)First
methods, is to have a NFS shared where session will be store. Setting this is quite easy, just a
little modification on php.ini file to change the “session.save_path ? directive to point to the
NFS share. The main problem with NFS is on high traffic, NFS share is really slow. So
synchronisation and data corruption can arrive and ....!
How to capture content from the output buffer ? or Give me an example for Output caching
in php?
<?php ob_start(); // start an output buffer echo ‘This text is from the w3answers
buffer*******<br />’; // output that will be stored in the buffer $w3buffer =
ob_get_contents(); // store buffer content in $w3buffer variable ob_end_clean(); // stop and
clean the output buffer echo ‘This is not from the w3answers buffer!!!!!!!!<br />’; echo
$w3buffer; ?> O/p
What is the difference between include and include_once?
include() The include() statement includes and evaluates the specified file. This also applies
to require(). The two constructs are identical in every way except how they handle failure.
include() produces a Warning while require() results in a Fatal Error. In other words, use
require() if you want a missing file to halt processing of the page. include() does not behave
this way, the script will continue regardless. include_once() The include_once() statement
includes and evaluates the specified file during the execution ....!
What are static methods?
Static Keyword Declaring class members or methods as static makes them accessible without
needing an instantiation of the class. A member declared as static can not be accessed with an
instantiated class object (though a static method can). The static declaration must be after the
visibility declaration. For compatibility with PHP 4, if no visibility declaration is used, then
the member or method will be treated as if it was declared as public. Because static methods
are callable without an instance of the object created, the p....!
what are the advantages of storing sessions in database?
If you store a session in a database you have several advantages: @ Improving the security
because on many hosting packages (shared host) PHP uses the same path for storing sessions
for all the users, somewhere that is not in your folders. @ You can track who is online etc. @
For application that are running on multiple servers, you can store all the session data in one
database. The real beauty of this approach is that you don't have to mod....!
Do you know about Cross site Scripting ?
Cross-site scripting (XSS) is a security exploit in which the attacker inserts malicious coding
into an link that appears to be from a trustworthy source. When someone clicks on the link,
the embedded programming is submitted as part of the client's Web request and can execute
on the user's computer, typically allowing the attacker to steal information. Web forms that
dynamically return an error message including user input data make it possible for attackers
to alter the HTML that controls the behavior of the form and/or the page. Attackers....!
Cross-site scripting (XSS) is a security exploit in which the attacker inserts malicious coding
into an link that appears to be from a trustworthy source. When someone clicks on the link,
the embedded programming is submitted as part of the client's Web request and can execute
on the user's computer, typically allowing the attacker to steal information.

Web forms that dynamically return an error message including user input data make it
possible for attackers to alter the HTML that controls the behavior of the form and/or the
page. Attackers....!

1. How can we get second of the current time using date function?
2. How can we know the number of elements in an array using php?
3. What are the different functions in sorting an array?
4. What would the following code print to the browser? Why?
5. How can you get round the stateless nature of HTTP using PHP?
6. What function can you use to open a file for reading and writing?
7. What function would you use to redirect the browser to a new page?
8. what is scandir() ?
9. what output do you get here?
10. what is the output here?
11. what is the output below mentioned
12. what is the output below mentioned ?
13. what is the output below mentioned?
14. What is the output for the following script ?
15. php comments will be?
16. php supports following database

1. How many HTTP headers will send to a web page(client side) from server when you
use sessions (session_start()) in php ?.
2. what are the advantages of storing sessions in database?
3. How to get the contents of a web page using php?
4. what are the security tips you should know before developing php/mysql web pages ?
5. what are the database space-saving functions available in php ?
6. what you should know about cookies before start using in php?
7. Given a line of text $string, how would you write a regular expression to strip all the
HTML tags from it?
8. what are the ways to check image mime types in php?
9. how to opening excel files in windows nad linux using php ?
10. How many ways your web server can utilize PHP to generate web pages?
11. What is meant by Persistent Database Connections?
12. List out some session functions in php?
13. Explain Parse Errors ? what are the most common causes of parse errors ?
14. what are the 'function problems' you have met in php?
15. Will persistent connection work in the CGI version of php ? mysql_connect() vs
mysql_pconnect()?
16. What is the process that takes place when you upload a file in php?
17. How do I prevent Web browsers caching a page in php?
18. what is Memcache?
19. Are php strings immutable ?
20. What Are PHP Arrays?
21. what is the php solution to dynamic caching ?
22. what are the most common caching policy approaches ?
23. What is the difference between $message and $$message?
24. How to capture content from the output buffer ? or Give me an example for Output
caching in php?
25. How to capture content from the output buffer ? or Give me an example for Output
caching in php?
26. which is faster mysql_unbuffered_query or mysql_query ?
27. why should we use Object oriented concepts in php ?
28. How can we extract string "w3answers.com" from a string
mailto:info@w3answers.com using regular expression of PHP ?
29. what is the output ?
30. what is the output here ?
31. Which function in PHP gives us absolute path of a file on the server?
32. Which of the following functions is most efficient for substituting fixed patterns in
strings?
33. what output do you get here?
34. PHP Functions for WDDX
35. Which of the following represents the proper way to set a session variable?
36. How we can pass data from PHP to ASP,ASP.net?
37. How to convert ASP Arrays to PHP and viceversa ?
38. Installing PHP on your Computer?
39. What is Apache?
40. What Storage Engines do you use in MySQL?
41. How can you block certain IP Addresses from accessing your site?
42. Your first PHP script - "Hello World"
43. What can PHP do?
44. What is PHP?

Define encapsulation? differ interface and abstract? differenciate www and internet?
....!
What is Phishing?
In computing, phishing is a form of criminal activity using social engineering techniques. It is
characterized by attempts to fraudulently acquire sensitive information, such as passwords
and credit card details, by masquerading as a trustworthy person or business in an apparently
official electronic communication. Phishing is typically carried out using email or an instant
message. The term phishing derives from password harvesting and the use of increasingly
sophisticated lures to "fish" for users' financial information and passwords.
What is the difference between strstr() and stristr()?
strstr -- Find first occurrence of a string strstr() example <?php$email = 'user@example.com';
$domain = strstr($email, '@');echo $domain; // prints @example.com?> stristr -- Case-
insensitive strstr() stristr() example <?php$email = 'USER@EXAMPLE.com';echo
stristr($email, 'e');// outputs ER@EXAMPLE. ....!
what are the most common caching policy approaches ?
1)Time triggered caching (expiry timestamp). 2)Content change triggered caching (sensitive
content has changed, so cache must be updated). 3)Manually triggered caching (manually
inform the application that information is outdated, and force a new cache creation). ....!
what is the use of –i-am-a-dummy flag in MySql?
It Makes the MySQL engine refuse UPDATE and DELETE commands where the WHERE
clause is not present. ....!
How to determine the number of rows in the full result set and also restrict the number of
rows that a query returns,without running a second query ?
Most of the developers using 2 queries to find total number of rows and limit,when we need
pagination(1,2,3,4). why should we write 2 queries to find limit as well as total number of
rows in a table. we can achieve this in a single query. eg: SELECT
SQL_CALC_FOUND_ROWS * FROM tbl_name WHERE id > 567 LIMIT 10; So
SQL_CALC_FOUND_ROWS can be useful in situations when you want to restrict the
number of rows that a query returns, but also determine the number of rows ....!
What function can you use to open a file for reading and writing?
1. fget(); 2. file_open(); 3. fopen(); 4. open_file(); ANS:fopen(); ....!
How to capture content from the output buffer ? or Give me an example for Output caching
in php?
<?php ob_start(); // start an output buffer echo ‘This text is from the w3answers
buffer*******<br />’; // output that will be stored in the buffer $w3buffer =
ob_get_contents(); // store buffer content in $w3buffer variable ob_end_clean(); // stop and
clean the output buffer echo ‘This is not from the w3answers buffer!!!!!!!!<br />’; echo
$w3buffer; ?> O/p
How can we encrypt and decrypt a data present in a MySQL table using MySQL?
There are two methods AES_ENCRYPT () and AES_DECRYPT () ....!
what is the output here ?
<?php session_start(); $_SESSION["var"] = NULL; echo $var = "www.w3answers.com"; ?>
The output : www.w3answers.com and warning as below Warning: Unknown: Your script
possibly relies on a session side-effect which existed until PHP 4.2.3. Please be advised that
the session extension does not consider global variables as a ....!
Tell me some thing about mod_rewrite and url rewriting?
mod_rewrite*************Simply, mod_rewrite is used for rewriting a URL at the server
level, giving the user output for that final page. So, for example, a user may ask for
http://www.referads.com/example/blue/, but will really be given
http://www.referads.com/example.php?colour=blue by the server. Of course, the user will
b....!
What is the difference between GROUP BY and ORDER BY in MySQL?
ORDER BY [col1],[col2],…,[coln]; Tels DBMS according to what columns it should sort the
result. If two rows will hawe the same value in col1 it will try to sort them according to col2
and so on. GROUP BY [col1],[col2],…,[coln]; Tels DBMS to group results with same value
of column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if you want to
count all items in group, sum all values or view average ....!
What is meant by Persistent Database Connections?
Persistent connections are links that do not close when the execution of your script ends.
When a persistent connection is requested, PHP checks if there's already an identical
persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does
not exist, it creates the link. An 'identical' connection is a connection that was opened to the
same host, with the same username and the same password (where applicable). Note *****
People who aren't thoroughly familiar with the way ....!
what is the output ?
<?php echo "www.w3answers.com"; if ((string)'-1') { print 'ouch'; } else { print 'echo'; } ?> a.
ouch b. echo c. none d. Parse error ANS: a ....!
What Storage Engines do you use in MySQL?
MySQL Engines MyISAM HEAP MEMORY MERGE MRG_MYISAM ISAM
MRG_ISAM InnoDB INNOBASE BDB BERKELEYDB NDBCLUSTER NDB EXAMPLE
ARCHIVE CSV   ....!

MySQL Engines

MyISAM

HEAP

MEMORY

MERGE

MRG_MYISAM

ISAM

MRG_ISAM

InnoDB

INNOBASE

BDB

BERKELEYDB

NDBCLUSTER

NDB

EXAMPLE

ARCHIVE

CSV
1. What is str_split function in php?
2. What's foreign data in php?
3. How do you convert an old fashioned 10 digit ISBN to a new 13 digit ISBN using php
?
4. what is session_start() ?
5. Is it possible to pass data from JavaScript to PHP?
6. What is MIME?
7. What is the difference between GROUP BY and ORDER BY in MySQL?
8. What is the functionality of md5 function in PHP?
9. What is the difference between char and varchar data types?
10. What are the commands to find the structure of a MySQL table other than EXPLAIN
command?
11. What is the maximum length for database, table & column names?
12. How can we repair a MySQL table?
13. What is meant by urlencode and urldecode?
14. What is the difference between the functions unlink() and unset()?
15. How can we know the count/number of elements of an array?
16. What is meant by PEAR in php?
17. What is the difference between strstr() and stristr()?
18. What is the difference between GET and POST methods in form submitting? Give the
cases where we can use GET and POST methods?
19. How can we submit a form without a submit button?
20. What is the difference between mysql_fetch_object and mysql_fetch_array?
21. What is Model-view-controller (MVC)?
22. What is Model-view-controller (MVC)?
23. What is smarty?
24. Authentication - General Definition
25. What is session hijacking?
26. Do you know about Cross site Scripting ?
27. What is Phishing?
28. What are static methods?
29. Tell me some thing about mod_rewrite and url rewriting?
30. What is the difference between include and include_once?
31. How does Database handle Sessions?
32. What is meant by Session Clustering?
33. What is meant by Session Clustering?
34. What is meant by Virtual hosting?
35. What is meant by Exceptional Handling?
36. What is the difference between constructors in PHP4 & PHP5?
37. What is AJAX?
38. What are the differences between Get and post methods in form submitting, give the
case where we can use get and we can use post methods?
39. Who is the father of PHP and explain the changes in PHP versions?
40. How can we submit a form without a submit button?
41. In how many ways we can retrieve the date in the result set of mysql using PHP?
42. What is the difference between mysql_fetch_object and mysql_fetch_array?
43. What is the difference between $message and $$message?
44. How can we extract string ‘techinterviews.com ‘ from a string
‘http://www.techinterviews.com’ using regular expression of PHP?
45. How can we create a database using PHP and mysql?
46. What are the differences between require and include, include_once?
47. Can we use include (”techinterviews.php”) two times in a PHP page “makeit.PHP”?
48. What are the different tables present in mysql, which type of table is generated when
we are creating a table in the following syntax: create table employee(eno
int(2),ename varchar(10)) ?
49. Functions in IMAP, POP3 AND LDAP?
50. How can I execute a PHP script using command line?
51. Suppose your Zend engine supports the mode <? ?> Then how can u configure your
PHP Zend engine to support <?PHP ?> mode ?
52. Shopping cart online validation i.e. how can we configure Paypal, etc.?
53. What is meant by nl2br()?
54. Draw the architecture of Zend engine?
55. What are the current versions of apache, PHP, and mysql?
56. What are the reasons for selecting lamp (linux, apache, mysql, PHP) instead of
combination of other software programmes, servers and operating systems?
57. How can we encrypt and decrypt a data present in a mysql table using mysql?
58. How can we encrypt the username and password using PHP?
59. What are the features and advantages of object-oriented programming?
60. What are the differences between procedure-oriented languages and object-oriented
languages?
61. What is the use of friend function?
62. What are the differences between public, private, protected, static, transient, final and
volatile?
63. What are the different types of errors in PHP?
64. What is the functionality of the function strstr and stristr?
65. What are the differences between PHP 3 and PHP 4 and PHP 5?
66. How can we convert asp pages to PHP pages?
67. What is the functionality of the function htmlentities?
68. How can we get second of the current time using date function?
69. How can we convert the time zones using PHP?
70. What is meant by urlencode and urldocode?
71. What is the difference between the functions unlink and unset?
72. How can we register the variables into a session?
73. How can we get the properties (size, type, width, height) of an image using PHP
image functions?
74. How can we get the browser properties using PHP?
75. What is the maximum size of a file that can be uploaded using PHP and how can we
change this?
76. How can we increase the execution time of a PHP script?
77. How can we take a backup of a mysql table and how can we restore it. ?
78. How can we optimize or increase the speed of a mysql select query?
79. How many ways can we get the value of current session id?
80. How can we destroy the session, how can we unset the variable of a session?
81. How can we destroy the cookie?
82. How many ways we can pass the variable through the navigation between the pages?
83. What is the difference between ereg_replace() and eregi_replace()?
84. What are the different functions in sorting an array?
85. How can we know the count/number of elements of an array?
86. What is the PHP predefined variable that tells the What types of images that PHP
supports?
87. How can I know that a variable is a number or not using a JavaScript?
88. List out some tools through which we can draw E-R diagrams for mysql.
89. How can I retrieve values from one database server and store them in other database
server using PHP?
90. List out the predefined classes in PHP?
91. How can I make a script that can be bilanguage (supports English, German)?
92. What are the difference between abstract class and interface?
93. How can we send mail using JavaScript?

PHP interview questions and answers


By admin | December 12, 2005

1. What does a special set of tags <?= and ?> do in PHP? - The output is displayed directly to
the browser.
2. What’s the difference between include and require? - It’s how they handle failures. If the
file is not found by require(), it will cause a fatal error and halt the execution of the script. If
the file is not found by include(), a warning will be issued, but execution will continue.
3. I am trying to assign a variable the value of 0123, but it keeps coming up with a different
number, what’s the problem? - PHP Interpreter treats numbers beginning with 0 as octal.
Look at the similar PHP interview questions for more numeric problems.
4. Would I use print "$a dollars" or "{$a} dollars" to print out the amount of dollars in this
example? - In this example it wouldn’t matter, since the variable is all by itself, but if you
were to print something like "{$a},000,000 mln dollars", then you definitely need to use the
braces.
5. How do you define a constant? - Via define() directive, like define ("MYCONSTANT", 100);
6. How do you pass a variable by value? - Just like in C++, put an ampersand in front of it, like
$a = &$b
7. Will comparison of string "10" and integer 11 work in PHP? - Yes, internally PHP will cast
everything to the integer type, so numbers 10 and 11 will be compared.
8. When are you supposed to use endif to end the conditional statement? - When the original
if was followed by : and then the code block without braces.
9. Explain the ternary conditional operator in PHP? - Expression preceding the ? is evaluated,
if it’s true, then the expression preceding the : is executed, otherwise, the expression
following : is executed.
10. How do I find out the number of parameters passed into function? - func_num_args()
function returns the number of parameters passed in.
11. If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $
$b? - 100, it’s a reference to existing variable.
12. What’s the difference between accessing a class method via -> and via ::? - :: is allowed to
access methods that can perform static operations, i.e. those, which do not require object
initialization.
13. Are objects passed by value or by reference? - Everything is passed by value.
14. How do you call a constructor for a parent class? - parent::constructor($value)
15. What’s the special meaning of __sleep and __wakeup? - __sleep returns the array of all the
variables than need to be saved, while __wakeup retrieves them.
16. Why doesn’t the following code print the newline properly?    <?php
            $str = ‘Hello, there.nHow are you?nThanks for visiting TechInterviews’;
            print $str;
    ?>
Because inside the single quotes the n character is not interpreted as newline, just as a
sequence of two characters - and n.
17. Would you initialize your strings with single quotes or double quotes? - Since the data
inside the single-quoted string is not parsed for variable substitution, it’s always a better
idea speed-wise to initialize a string with single quotes, unless you specifically need variable
substitution.
18. How come the code <?php print "Contents: $arr[1]"; ?> works, but <?php print "Contents:
$arr[1][2]"; ?> doesn’t for two-dimensional array of mine? - Any time you have an array
with more than one dimension, complex parsing syntax is required. print "Contents: {$arr[1]
[2]}" would’ve worked.
19. What is the difference between characters �23 and x23? - The first one is octal 23, the
second is hex 23.
20. With a heredoc syntax, do I get variable substitution inside the heredoc contents? - Yes.
21. I want to combine two variables together:
22. $var1 = 'Welcome to ';
23. $var2 = 'TechInterviews.com';

What will work faster? Code sample 1:

$var 3 = $var1.$var2;

Or code sample 2:

$var3 = "$var1$var2";

Both examples would provide the same result - $var3 equal to "Welcome to
TechInterviews.com". However, Code Sample 1 will work significantly faster. Try it
out with large sets of data (or via concatenating small sets a million times or so), and
you will see that concatenation works significantly faster than variable substitution.

24. For printing out strings, there are echo, print and printf. Explain the differences. - echo is
the most primitive of them, and just outputs the contents following the construct to the
screen. print is also a construct (so parentheses are optional when calling it), but it returns
TRUE on successful output and FALSE if it was unable to print out the string. However, you
can pass multiple parameters to echo, like:

<?php echo 'Welcome ', 'to', ' ', 'TechInterviews!'; ?>

and it will output the string "Welcome to TechInterviews!" print does not take
multiple parameters. It is also generally argued that echo is faster, but usually the
speed advantage is negligible, and might not be there for future versions of PHP.
printf  is a function, not a construct, and allows such advantages as formatted output,
but it’s the slowest way to print out data out of echo, print and printf.

25. I am writing an application in PHP that outputs a printable version of driving directions. It
contains some long sentences, and I am a neat freak, and would like to make sure that no
line exceeds 50 characters. How do I accomplish that with PHP? - On large strings that need
to be formatted according to some length specifications, use wordwrap() or chunk_split().
26. What’s the output of the ucwords function in this example?
27. $formatted = ucwords("TECHINTERVIEWS IS COLLECTION OF
INTERVIEW QUESTIONS");
print $formatted;
What will be printed is TECHINTERVIEWS IS COLLECTION OF INTERVIEW
QUESTIONS.
ucwords() makes every first letter of every word capital, but it does not lower-case
anything else. To avoid this, and get a properly formatted string, it’s worth using
strtolower() first.

28. What’s the difference between htmlentities() and htmlspecialchars()? - htmlspecialchars


only takes care of <, >, single quote ‘, double quote " and ampersand. htmlentities translates
all occurrences of character sequences that have different meaning in HTML.
29. What’s the difference between md5(), crc32() and sha1() crypto on PHP? - The major
difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1()
returns a 128 bit value, and md5() returns a 160 bit value. This is important when avoiding
collisions.
30. So if md5() generates the most secure hash, why would you ever use the less secure
crc32() and sha1()? - Crypto usage in PHP is simple, but that doesn’t mean it’s free. First off,
depending on the data that you’re encrypting, you might have reasons to store a 32-bit
value in the database instead of the 160-bit value to save on space. Second, the more secure
the crypto is, the longer is the computation time to deliver the hash value. A high volume
site might be significantly slowed down, if frequent md5() generation is required.
31. How do you match the character ^ at the beginning of the string? - ^^

Mysql

29 MySQL interview questions


By admin | September 5, 2006

1. How do you start and stop MySQL on Windows? - net start MySQL, net stop MySQL
2. How do you start MySQL on Linux? - /etc/init.d/mysql start
3. Explain the difference between mysql and mysqli interfaces in PHP? - mysqli is the object-
oriented version of mysql library functions.
4. What’s the default port for MySQL Server? - 3306
5. What does tee command do in MySQL? - tee followed by a filename turns on MySQL
logging to a specified file. It can be stopped by command notee.
6. Can you save your connection settings to a conf file? - Yes, and name it ~/.my.conf. You
might want to change the permissions on the file to 600, so that it’s not readable by others.
7. How do you change a password for an existing user via mysqladmin? - mysqladmin -u root
-p password "newpassword"
8. Use mysqldump to create a copy of the database? - mysqldump -h mysqlhost -u username
-p mydatabasename > dbdump.sql
9. Have you ever used MySQL Administrator and MySQL Query Browser? Describe the tasks
you accomplished with these tools.
10. What are some good ideas regarding user security in MySQL? - There is no user without a
password. There is no user without a user name. There is no user whose Host column
contains % (which here indicates that the user can log in from anywhere in the network or
the Internet). There are as few users as possible (in the ideal case only root) who have
unrestricted access.
11. Explain the difference between MyISAM Static and MyISAM Dynamic. - In MyISAM static all
the fields have fixed width. The Dynamic MyISAM table would include fields such as TEXT,
BLOB, etc. to accommodate the data types with various lengths. MyISAM Static would be
easier to restore in case of corruption, since even though you might lose some data, you
know exactly where to look for the beginning of the next record.
12. What does myisamchk do? - It compressed the MyISAM tables, which reduces their disk
usage.
13. Explain advantages of InnoDB over MyISAM? - Row-level locking, transactions, foreign key
constraints and crash recovery.
14. Explain advantages of MyISAM over InnoDB? - Much more conservative approach to disk
space management - each MyISAM table is stored in a separate file, which could be
compressed then with myisamchk if needed. With InnoDB the tables are stored in
tablespace, and not much further optimization is possible. All data except for TEXT and BLOB
can occupy 8,000 bytes at most. No full text indexing is available for InnoDB. TRhe
COUNT(*)s execute slower than in MyISAM due to tablespace complexity.
15. What are HEAP tables in MySQL? - HEAP tables are in-memory. They are usually used for
high-speed temporary storage. No TEXT or BLOB fields are allowed within HEAP tables. You
can only use the comparison operators = and <=>. HEAP tables do not support
AUTO_INCREMENT. Indexes must be NOT NULL.
16. How do you control the max size of a HEAP table? - MySQL config variable
max_heap_table_size.
17. What are CSV tables? - Those are the special tables, data for which is saved into comma-
separated values files. They cannot be indexed.
18. Explain federated tables. - Introduced in MySQL 5.0, federated tables allow access to the
tables located on other databases on other servers.
19. What is SERIAL data type in MySQL? - BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT
20. What happens when the column is set to AUTO INCREMENT and you reach the maximum
value for that table? - It stops incrementing. It does not overflow to 0 to prevent data losses,
but further inserts are going to produce an error, since the key has been used already.
21. Explain the difference between BOOL, TINYINT and BIT. - Prior to MySQL 5.0.3: those are all
synonyms. After MySQL 5.0.3: BIT data type can store 8 bytes of data and should be used for
binary data.
22. Explain the difference between FLOAT, DOUBLE and REAL. - FLOATs store floating point
numbers with 8 place accuracy and take up 4 bytes. DOUBLEs store floating point numbers
with 16 place accuracy and take up 8 bytes. REAL is a synonym of FLOAT for now.
23. If you specify the data type as DECIMAL (5,2), what’s the range of values that can go in this
table? - 999.99 to -99.99. Note that with the negative number the minus sign is considered
one of the digits.
24. What happens if a table has one column defined as TIMESTAMP? - That field gets the
current timestamp whenever the row gets altered.
25. But what if you really want to store the timestamp data, such as the publication date of
the article? - Create two columns of type TIMESTAMP and use the second one for your real
data.
26. Explain data type TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP - The column exhibits the same behavior as a single timestamp
column in a table with no other timestamp columns.
27. What does TIMESTAMP ON UPDATE CURRENT_TIMESTAMP data type do? - On
initialization places a zero in that column, on future updates puts the current value of the
timestamp in.
28. Explain TIMESTAMP DEFAULT ‘2006:09:02 17:38:44′ ON UPDATE CURRENT_TIMESTAMP. -
A default value is used on initialization, a current timestamp is inserted on update of the
row.
29. If I created a column with data type VARCHAR(3), what would I expect to see in MySQL
table? - CHAR(3), since MySQL automatically adjusted the data type.

Q:1 What are the differences between Get and post methods in form submitting.
give the case where we can use get and we can use post methods? A:1

When to use GET or POST

The HTML 2.0 specification says, in section Form


Submission (and the HTML 4.0 specification repeats this with minor
stylistic changes):

–>If the processing of a form is idempotent


(i.e. it has no lasting observable effect on the state of the
world), then the form method should be GET. Many database searches
have no visible side-effects and make ideal applications of query
forms.

–>If the service associated with the processing of a form has side
effects (for example, modification of a database or subscription to
a service), the method should be POST.

How the form data is transmitted?

quotation from the HTML 4.0 specification

–> If the method is “get” – -, the user agent


takes the value of action, appends a ? to it, then appends the form
data set, encoded using the application/x-www-form-urlencoded
content type. The user agent then traverses the link to this URI. In
this scenario, form data are restricted to ASCII codes.
–> If the method is “post” –, the user agent conducts an HTTP post
transaction using the value of the action attribute and a message
created according to the content type specified by the enctype
attribute.
Quote from CGI FAQ

Firstly, the the HTTP protocol specifies


differing usages for the two methods. GET requests should always be
idempotent on the server. This means that whereas one GET request
might (rarely) change some state on the Server, two or more
identical requests will have no further effect.

This is a theoretical point which is also good


advice in practice. If a user hits “reload” on his/her browser, an
identical request will be sent to the server, potentially resulting
in two identical database or
guestbook entries, counter increments, etc. Browsers may reload a
GET URL automatically, particularly if cacheing is disabled (as is
usually the case with CGI output), but will typically prompt the
user before
re-submitting a POST request. This means you’re far less likely to
get inadvertently-repeated entries from POST.

GET is (in theory) the preferred method for


idempotent operations, such as querying a database, though it
matters little if you’re using a form. There is a further practical
constraint that many systems have built-in limits to the length of a
GET request they can handle: when the total size of a request (URL+params)
approaches or exceeds 1Kb, you are well-advised to use POST in any
case.

I would prefer POST when I don’t want the status to


be change when user resubmits. And GET
when it does not matter.

    Q:2 Who is the father of PHP and explain the changes in PHP versions?
A:2 Rasmus Lerdorf is known as the father of PHP.PHP/FI 2.0 is an early and no longer supported
version of PHP. PHP 3
is the successor to PHP/FI 2.0 and is a lot nicer. PHP 4 is the current
generation of PHP, which uses the
Zend engine
under the
hood. PHP 5 uses
Zend engine 2 which,
among other things, offers many additionalOOP features     Q:3 How can we submit a form without
a submit button? A:3 The main idea behind this is to use Java script submit() function in
order to submit the form without explicitly clicking any submit button.
You can attach the document.formname.submit() method to onclick,
onchange events of different inputs and perform the form submission. you
can even built a timer function where you can automatically submit the
form after xx seconds once the loading is done (can be seen in online
test sites).     Q:4 In how many ways we can retrieve the data in the result set of
MySQL using PHP? A:4 You can do it by 4 Ways1. mysql_fetch_row.
2. mysql_fetch_array
3. mysql_fetch_object
4. mysql_fetch_assoc     Q:5 What is the difference between mysql_fetch_object and
mysql_fetch_array? A:5 mysql_fetch_object() is similar tomysql_fetch_array(), with one difference
-
an object is returned, instead of an array. Indirectly, that means that
you can only access the data by the field names, and not by their
offsets (numbers are illegal property names).     Q:6 What is the difference between $message and
$$message? A:6 It is a classic example of PHP’s variable variables. take the
following example.$message = “Mizan”;$$message = “is a moderator of PHPXperts.”;$message is a
simple PHP variable that we are used to. But the
$$message is not a very familiar face. It creates a variable name $mizan
with the value “is a moderator of PHPXperts.” assigned. break it like
this${$message} => $mizanSometimes it is convenient to be able to have variable variable
names. That is, a variable name which can be set and used dynamically.     Q:7 How can we extract
string ‘abc.com ‘ from a string ‘http://info@abc.com’
using regular expression of PHP? A:7 preg_match(“/^http:\/\/.+@(.+)$/”,’http://info@abc.com’,
$found);
echo $found[1];     Q:8 How can we create a database using PHP and MySQL? A:8 We can create
MySQL database with the use of
mysql_create_db(“Database Name”)     Q:9 What are the differences between require and include,
include_once and require_once? A:9

The include() statement includes


and evaluates the specified file.The documentation below also applies to
require(). The two constructs
are identical in every way except how they handle
failure. include() produces a
Warning while require() results
in a Fatal Error. In other words, use
require() if you want a missing
file to halt processing of the page.
include() does not behave this way, the script will
continue regardless.

The include_once()
statement includes and evaluates the
specified file during the execution of
the script. This is a behavior similar
to the include()
statement, with the only difference
being that if the code from a file has
already been included, it will not be
included again. As the name suggests, it
will be included just once.include_once()
should be used in cases where the same
file might be included and evaluated
more than once during a particular
execution of a script, and you want to
be sure that it is included exactly once
to avoid problems with function
redefinitions, variable value
reassignments, etc.

require_once()
should be used in cases where the same
file might be included and evaluated
more than once during a particular
execution of a script, and you want to
be sure that it is included exactly once
to avoid problems with function
redefinitions, variable value
reassignments, etc.

    Q:10 Can we use include (”abc.PHP”) two times in a PHP page “makeit.PHP”?
A:10 Yes we can use include() more than one time in any page though it is
not a very good practice.     Q:11 What are the different tables present in MySQL, which type of
table is generated when we are creating a table in the following syntax:
create table employee (eno int(2),ename varchar(10)) ? A:11 Total 5 types of tables we can create
1. MyISAM
2. Heap
3. Merge
4. INNO DB
5. ISAM
MyISAM is the default storage engine as of MySQL 3.23 and as a result if
we do not specify the table name explicitly it will be assigned to the
default engine.     Q:12 Functions in IMAP, POP3 AND LDAP? A:12 You can find these specific
information in PHP Manual.     Q:13 How can I execute a PHP script using command line? A:13 As of
version 4.3.0, PHP supports a new SAPI type (Server
Application Programming Interface) named CLI which means Command Line
Interface. Just run the PHP CLI (Command Line Interface) program and
provide the PHP script file name as the command line argument. For
example, “php myScript.php”, assuming “php” is the command to invoke the
CLI program.
Be aware that if your PHP script was written for the Web CGI interface,
it may not execute properly in command line environment.     Q:14 Suppose your Zend engine
supports the mode <? ?> Then how can u
configure your PHP Zend engine to support <?PHP ?> mode ? A:14 In php.ini file:
set
short_open_tag=on
to make PHP support     Q:15 Shopping cart online validation i.e. how can we configure Paypal,
etc.? A:15 We can find the detail documentation about different paypal
integration process at the following site
PayPal PHP
SDK : http://www.paypaldev.org

    Q:16 What is meant by nl2br()? A:16 Inserts HTML line breaks (<BR />) before all newlines in a
string
string nl2br (string); Returns string with ” inserted before all
newlines. For example: echo nl2br(“god bless\n you”) will output “god
bless <br /> you” to your browser.     Q:17 Draw the architecture of Zend engine? A:17 The Zend
Engine is the internal compiler and runtime engine used by
PHP4. Developed by Zeev Suraski and Andi Gutmans, the Zend Engine is an
abbreviation of their names. In the early days of PHP4, it worked as
follows:

The PHP script was loaded by the Zend Engine and


compiled into Zend
opcode. Opcodes, short for operation codes, are low level binary
instructions. Then the opcode was executed and the HTML generated sent
to the client. The opcode was flushed from memory after execution.Today, there are a multitude of
products and techniques to help you
speed up this process. In the following diagram, we show the how modern
PHP scripts work; all the shaded boxes are optional.
PHP Scripts are loaded into
memory and compiled into Zend opcodes.     Q:18 What are the current versions of apache, PHP,
and MySQL? A:18 As of February, 2007 the current versions arePHP: php5.2.1
MySQL: MySQL 5.2
Apache: Apache 2.2.4Note: visit www.php.net,

http://dev.mysql.com/downloads/mysql/,

www.apache.org to get current


versions.

    Q:19 What are the reasons for selecting lamp (Linux, apache, MySQL,
PHP) instead of combination of other software programs, servers and
operating systems? A:19 All of those are open source resource. Security of Linux is very
very more than windows. Apache is a better server that IIS both in
functionality and security. MySQL is world most popular open source
database. PHP is more faster that asp or any other scripting language.     Q:20 How can we encrypt
and decrypt a data present in a MySQL table
using MySQL? A:20 AES_ENCRYPT () and AES_DECRYPT ()     Q:21 How can we encrypt the username
and password using PHP? A:21 The functions in this section perform encryption and decryption, and
compression and uncompression:

encryption decryption

AES_ENCRYT() AES_DECRYPT()

ENCODE() DECODE()

DES_ENCRYPT() DES_DECRYPT()

ENCRYPT() Not available

MD5() Not available

OLD_PASSWORD() Not available


PASSWORD() Not available

SHA() or SHA1() Not available

Not available UNCOMPRESSED_LENGTH()

    Q:22 What are the features and advantages of object-oriented


programming? A:22 One of the main advantages of OO programming is its ease of
modification; objects can easily be modified and added to a system there
by reducing maintenance costs. OO programming is also considered to be
better at modeling the real world than is procedural programming. It
allows for more complicated and flexible interactions. OO systems are
also easier for non-technical personnel to understand and easier for
them to participate in the maintenance and enhancement of a system
because it appeals to natural human cognition patterns.
For some systems, an OO approach can speed development time since many
objects are standard across systems and can be reused. Components that
manage dates, shipping, shopping carts, etc. can be purchased and easily
modified for a specific system     Q:23 What are the differences between procedure-oriented
languages and
object-oriented languages? A:23 Traditional programming has the following
characteristics:Functions are written sequentially, so that a change in programming can
affect any code that follows it.
If a function is used multiple times in a system (i.e., a piece of code
that manages the date), it is often simply cut and pasted into each
program (i.e., a change log, order function, fulfillment system, etc).
If a date change is needed (i.e., Y2K when the code needed to be changed
to handle four numerical digits instead of two), all these pieces of
code must be found, modified, and tested.
Code (sequences of computer instructions) and data (information on which
the instructions operates on) are kept separate. Multiple sets of code
can access and modify one set of data. One set of code may rely on data
in multiple places. Multiple sets of code and data are required to work
together. Changes made to any of the code sets and data sets can cause
problems through out the system.Object-Oriented programming takes a radically different
approach:Code and data are merged into one indivisible item – an object (the
term “component” has also been used to describe an object.) An object is
an abstraction of a set of real-world things (for example, an object may
be created around “date”) The object would contain all information and
functionality for that thing (A date
object it may contain labels like January, February, Tuesday, Wednesday.
It may contain functionality that manages leap years, determines if it
is a business day or a holiday, etc., See Fig. 1). Ideally, information
about a particular thing should reside in only one place in a system.
The information within an object is encapsulated (or hidden) from the
rest of the system.
A system is composed of multiple objects (i.e., date function, reports,
order processing, etc., See Fig 2). When one object needs information
from another object, a request is sent asking for specific information.
(for example, a report object may need to know what today’s date is and
will send a request to the date object) These requests are called
messages and each object has an interface that manages messages.
OO programming languages include features such as “class”, “instance”,
“inheritance”, and “polymorphism” that increase the power and
flexibility of an object.     Q:24 What is the use of friend function? A:24 Sometimes a function is best
shared among a number of different
classes. Such functions can be declared either as member functions of
one class or as global functions. In either case they can be set to be
friends of other classes, by using a friend specifier in the class that
is admitting them. Such functions can use all attributes of the class
which names them as a friend, as if they were themselves members of that
class.
A friend declaration is essentially a prototype for a member function,
but instead of requiring an implementation with the name of that class
attached by the double colon syntax, a global function or member
function of another class provides the match.     Q:25 What are the differences between public,
private, protected,
static, transient, final and volatile? A:25 Public: Public declared items can be accessed everywhere.
Protected: Protected limits access to inherited and parent
classes (and to the class that defines the item).
Private: Private limits visibility only to the class that defines
the item.
Static: A static variable exists only in a local function scope,
but it does not lose its value when program execution leaves this scope.
Final: Final keyword prevents child classes from overriding a
method by prefixing the definition with final. If the class itself is
being defined final then it cannot be extended.
transient: A transient variable is a variable that may not
be serialized.
volatile: a variable that might be concurrently modified by multiple
threads should be declared volatile. Variables declared to be volatile
will not be optimized by the compiler because their value can change at
any time.     Q:26 What are the different types of errors in PHP? A:26 Three are three types of
errors:1. Notices: These are trivial,
non-critical errors that PHP encounters while executing a script – for
example, accessing a variable that has not yet been defined. By default,
such errors are not displayed to the user at all – although, as you will
see, you can change this default behavior.2. Warnings: These are more serious errors – for example,
attempting
to include() a file which does not exist. By default, these errors are
displayed to the user, but they do not result in script termination.3. Fatal errors: These are critical
errors – for example,
instantiating an object of a non-existent class, or calling a
non-existent function. These errors cause the immediate termination of
the script, and PHP’s default behavior is to display them to the user
when they take place.     Q:27 What is the functionality of the function strstr and stristr? A:27
strstr:

Returns part of haystack


string from the first occurrence of
needle to the end of
haystack.If needle is not found,
returns FALSE.

If needle is not a
string, it is converted to an integer and applied as the
ordinal value of a character.

This function is case-sensitive. For


case-insensitive searches, use
stristr().

    Q:28 What are the differences between PHP 3 and PHP 4 and PHP 5? A:28 Please read the
release notes at
http://www.php.net.     Q:29 How can we convert asp pages to PHP pages? A:29 there are lots of
tools available for asp to PHP conversion. you can
search Google for that. the best one is available athttp://asp2php.naken.cc./     Q:30 What is the
functionality of the function htmlentities? A:30 Convert all applicable characters to HTML entities
This function is identical to htmlspecialchars() in all ways, except
with htmlentities(), all characters which have HTML character entity
equivalents are translated into these entities.     Q:31 How can we get second of the current time
using date function?
A:31 $second = date(“s”);     Q:32 How can we convert the time zones using PHP? A:32 By using
date_default_timezone_get and
date_default_timezone_set function on PHP 5.1.0

<?php
// Discover what 8am in Tokyo relates to on the East Coast of the US

// Set the default timezone to Tokyo time:


date_default_timezone_set('Asia/Tokyo');

// Now generate the timestamp for that particular timezone, on Jan 1st,
2000
$stamp = mktime(8, 0, 0, 1, 1, 2000);

// Now set the timezone back to US/Eastern


date_default_timezone_set('US/Eastern');

// Output the date in a standard format (RFC1123), this will print:


// Fri, 31 Dec 1999 18:00:00 EST
echo '<p>', date(DATE_RFC1123, $stamp) ,'</p>';?>
    Q:33 What is meant by urlencode and urldocode? A:33 URLencode returns a string in which all
non-alphanumeric characters
except -_. have been replaced with a percent ( %)
sign followed by two hex digits and spaces encoded as plus ( +)
signs. It is encoded the same way that the posted data from a WWW form
is encoded, that is the same way as in
application/x-www-form-urlencoded media type.

urldecode decodes any %##


encoding in the given string.

    Q:34 What is the difference between the functions unlink and unset?
A:34 unlink() deletes the given file from the file system.
unset() makes a variable undefined.     Q:35 How can we register the variables into a session? A:35
$_SESSION[’name’] = “Mizan”;     Q:36 How can we get the properties (size, type, width, height) of
an
image using PHP image functions? A:36 To know the Image type use exif_imagetype () function
To know the Image size use getimagesize () function
To know the image width use imagesx () function
To know the image height use imagesy() function t     Q:37 How can we get the browser properties
using PHP? A:37 By using
$_SERVER['HTTP_USER_AGENT']
variable.
    Q:38 What is the maximum size of a file that can be uploaded using PHP
and how can we change this? A:38 By default the maximum size is 2MB. and we can change the
following
setup at php.iniupload_max_filesize = 2M     Q:39 How can we increase the execution time of a PHP
script? A:39 by changing the following setup at php.inimax_execution_time = 30
; Maximum execution time of each script, in seconds     Q:40 How can we take a backup of a MySQL
table and how can we restore
it. ? A:40 To backup: BACKUP TABLE tbl_name[,tbl_name…] TO
‘/path/to/backup/directory’
RESTORE TABLE tbl_name[,tbl_name…] FROM ‘/path/to/backup/directory’mysqldump: Dumping
Table Structure and DataUtility to dump a database or a collection of database for backup or
for transferring the data to another SQL server (not necessarily a MySQL
server). The dump will contain SQL statements to create the table and/or
populate the table.
-t, –no-create-info
Don’t write table creation information (the CREATE TABLE statement).
-d, –no-data
Don’t write any row information for the table. This is very useful if
you just want to get a dump of the structure for a table!     Q:41 How can we optimize or increase
the speed of a MySQL select
query? A:41
 first of all instead of using select * from table1, use select
column1, column2, column3.. from table1
 Look for the opportunity to introduce index in the table you are
querying.
 use limit keyword if you are looking for any specific number of
rows from the result set.

    Q:42 How many ways can we get the value of current session id? A:42 session_id() returns the
session id for the current session.     Q:43 How can we destroy the session, how can we unset the
variable of
a session? A:43 session_unregister — Unregister a global variable from the current
session
session_unset — Free all session variables     Q:44 How can we destroy the cookie? A:44 Set the
cookie in past.     Q:45 How many ways we can pass the variable through the navigation
between the pages? A:45

 GET/QueryString
 POST

    Q:46 What is the difference between ereg_replace() and eregi_replace()?


A:46 eregi_replace() function is identical to ereg_replace() except that
this ignores case distinction when matching alphabetic
characters.eregi_replace() function is identical to ereg_replace()
except that this ignores case distinction when matching alphabetic
characters.     Q:47 What are the different functions in sorting an array? A:47 Sort(), arsort(),
asort(), ksort(),
natsort(), natcasesort(),
rsort(), usort(),
array_multisort(), and
uksort().     Q:48 How can we know the count/number of elements of an array? A:48 2 ways
a) sizeof($urarray) This function is an alias of count()
b) count($urarray)     Q:49 What is the PHP predefined variable that tells the What types of
images that PHP supports? A:49 Though i am not sure if this is wrong or not, With the exif
extension you are able to work with image meta data.     Q:50 How can I know that a variable is a
number or not using a
JavaScript? A:50 bool is_numeric ( mixed var)
Returns TRUE if var is a number or a numeric string, FALSE otherwise.or use isNaN(mixed var)The
isNaN() function is used to check if a value is not a number.     Q:51 List out some tools through
which we can draw E-R diagrams for
mysql. A:51 Case Studio
Smart Draw     Q:52 How can I retrieve values from one database server and store them
in other database server using PHP? A:52 we can always fetch from one database and rewrite to
another. here
is a nice solution of it.$db1 = mysql_connect(“host”,”user”,”pwd”)
mysql_select_db(“db1″, $db1);
$res1 = mysql_query(“query”,$db1);$db2 = mysql_connect(“host”,”user”,”pwd”)
mysql_select_db(“db2″, $db2);
$res2 = mysql_query(“query”,$db2);At this point you can only fetch records from you previous
ResultSet,
i.e $res1 – But you cannot execute new query in $db1, even if you
supply the link as because the link was overwritten by the new db.so at this point the following script
will fail
$res3 = mysql_query(“query”,$db1); //this will failSo how to solve that?

take a look below.


$db1 = mysql_connect(“host”,”user”,”pwd”)
mysql_select_db(“db1″, $db1);
$res1 = mysql_query(“query”,$db1);

$db2 = mysql_connect(“host”,”user”,”pwd”, true)


mysql_select_db(“db2″, $db2);
$res2 = mysql_query(“query”,$db2);

So mysql_connect has another optional boolean parameter which


indicates whether a link will be created or not. as we connect to the
$db2 with this optional parameter set to ‘true’, so both link will
remain live.

now the following query will execute successfully.


$res3 = mysql_query(“query”,$db1);

Thanks goes to Hasan and Hasin for this solution.

    Q:53 List out the predefined classes in PHP? A:53 Directory


stdClass
__PHP_Incomplete_Class
exception
php_user_filter     Q:54 How can I make a script that can be bi-language (supports
English, German)? A:54 You can maintain two separate language file for each of the
language. all the labels are putted in both language files as variables
and assign those variables in the PHP source. on runtime choose the
required language option.     Q:55 What are the difference between abstract class and interface?
A:55 Abstract class: abstract classes are the class where one or more
methods are abstract but not necessarily all method has to be abstract.
Abstract methods are the methods, which are declare in its class but not
define. The definition of those methods must be in its extending class.Interface: Interfaces are one
type of class where all the methods are
abstract. That means all the methods only declared but not defined. All
the methods must be define by its implemented class.     Q:56 How can we send mail using
JavaScript? A:56 JavaScript does not have any networking capabilities as it is
designed to work on client site. As a result we can not send mails using
JavaScript. But we can call the client side mail protocol mailto
via JavaScript to prompt for an email to send. this requires the client
to approve it.     Q:57 How can we repair a MySQL table? A:57 The syntex for repairing a MySQL
table is
REPAIR TABLENAME, [TABLENAME, ], [Quick],[Extended]
This command will repair the table specified if the quick is given the
MySQL will do a repair of only the index tree if the extended is given
it will create index row by row     Q:58 What are the advantages of stored procedures, triggers,
indexes?
A:58 A stored procedure is a set of SQL commands that can be compiled and
stored in the server. Once this has been done, clients don’t need to
keep re-issuing the entire query but can refer to the stored procedure.
This provides better overall performance because the query has to be
parsed only once, and less information needs to be sent between the
server and the client. You can also raise the conceptual level by having
libraries of functions in the server. However, stored procedures of
course do increase the load on the database server system, as more of
the work is done on the server side and less on the client (application)
side.Triggers will also be implemented. A trigger is effectively a type of
stored procedure, one that is invoked when a particular event occurs.
For example, you can install a stored procedure that is triggered each
time a record is deleted from a transaction table and that stored
procedure automatically deletes the corresponding customer from a
customer table when all his transactions are deleted.Indexes are used to find rows with specific
column values quickly.
Without an index, MySQL must begin with the first row and then read
through the entire table to find the relevant rows. The larger the
table, the more this costs. If the table has an index for the columns in
question, MySQL can quickly determine the position to seek to in the
middle of the data file without having to look at all the data. If a
table has 1,000 rows, this is at least 100 times faster than reading
sequentially. If you need to access most of the rows, it is faster to
read sequentially, because this minimizes disk seeks.     Q:59 What is the maximum length of a table
name, database name, and
fieldname in MySQL? A:59 The following table describes the maximum length for each type of
identifier.

Maximum Length
Identifier
(bytes)

Database 64

Table 64

Column 64

Index 64

Alias 255
There are some restrictions on the characters that may appear in
identifiers:

    Q:60 How many values can the SET function of MySQL take? A:60 MySQL set can take zero or
more values but at the maximum it can
take 64 values     Q:61 What are the other commands to know the structure of table using
MySQL commands except explain command? A:61 describe Table-Name;     Q:62 How many tables
will create when we create table, what are they?
A:62 The ‘.frm’ file stores the table definition.
The data file has a ‘.MYD’ (MYData) extension.
The index file has a ‘.MYI’ (MYIndex) extension,     Q:63 What is the purpose of the following files
having extensions 1) .frm
2) .myd 3) .myi? What do these files contain? A:63 In MySql, the default table type is MyISAM.
Each MyISAM table is stored on disk in three files. The files have names
that begin with the table name and have an extension to indicate the
file type.
The ‘.frm’ file stores the table definition.
The data file has a ‘.MYD’ (MYData) extension.
The index file has a ‘.MYI’ (MYIndex) extension,     Q:64 What is maximum size of a database in
MySQL? A:64 If the operating system or filesystem places a limit on the number
of files in a directory, MySQL is bound by that constraint.The efficiency of the operating system in
handling large numbers of
files in a directory can place a practical limit on the number of tables
in a database. If the time required to open a file in the directory
increases significantly as the number of files increases, database
performance can be adversely affected.
The amount of available disk space limits the number of tables.
MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAM
storage engine in MySQL 3.23, the maximum table size was increased to
65536 terabytes (2567 – 1 bytes). With this larger allowed table size,
the maximum effective table size for MySQL databases is usually
determined by operating system constraints on file sizes, not by MySQL
internal limits.The InnoDB storage engine maintains InnoDB tables within a tablespace
that can be created from several files. This allows a table to exceed
the maximum individual file size. The tablespace can include raw disk
partitions, which allows extremely large tables. The maximum tablespace
size is 64TB.
The following table lists some examples of operating system file-size
limits. This is only a rough guide and is not intended to be definitive.
For the most up-to-date information, be sure to check the documentation
specific to your operating system.
Operating System File-size LimitLinux 2.2-Intel 32-bit 2GB (LFS: 4GB)
Linux 2.4+ (using ext3 filesystem) 4TB
Solaris 9/10 16TB
NetWare w/NSS filesystem 8TB
Win32 w/ FAT/FAT32 2GB/4GB
Win32 w/ NTFS 2TB (possibly larger)
MacOS X w/ HFS+ 2TB     Q:65 Give the syntax of Grant and Revoke commands? A:65 The generic
syntax for grant is as following
> GRANT [rights] on [database/s] TO [username@hostname] IDENTIFIED BY
[password]
now rights can be
a) All privileges
b) combination of create, drop, select, insert, update and delete etc.We can grant rights on all
databse by using *.* or some specific
database by database.* or a specific table by database.table_name
username@hotsname can be either username@localhost, username@hostname
and username@%
where hostname is any valid hostname and % represents any name, the *.*
any condition
password is simply the password of userThe generic syntax for revoke is as following
> REVOKE [rights] on [database/s] FROM [username@hostname]
now rights can be as explained above
a) All privileges
b) combination of create, drop, select, insert, update and delete etc.
username@hotsname can be either username@localhost, username@hostname
and username@%
where hostname is any valid hostname and % represents any name, the *.*
any condition     Q:66 Explain Normalization concept? A:66 The normalization process involves
getting our data to conform to
three progressive normal forms, and a higher level of normalization
cannot be achieved until the previous levels have been achieved (there
are actually five normal forms, but the last two are mainly academic and
will not be discussed).First Normal FormThe First Normal Form (or 1NF) involves removal of
redundant data
from horizontal rows. We want to ensure that there is no duplication of
data in a given row, and that every column stores the least amount of
information possible (making the field atomic).Second Normal FormWhere the First Normal Form
deals with redundancy of data across a
horizontal row, Second Normal Form (or 2NF) deals with redundancy of
data in vertical columns. As stated earlier, the normal forms are
progressive, so to achieve Second Normal Form, your tables must already
be in First Normal Form.Third Normal Form

I have a confession to make; I do not often use Third Normal Form. In


Third Normal Form we are looking for data in our tables that is not
fully dependant on the primary key, but dependant on another value in
the table

    Q:67 How can we find the number of rows in a table using MySQL? A:67 Use this for mysql
>SELECT COUNT(*) FROM table_name;     Q:68 How can we find the number of rows in a result set
using PHP? A:68 $result = mysql_query($sql, $db_link);
$num_rows = mysql_num_rows($result);
echo "$num_rows rows found";     Q:69 How many ways we can we find the current date
using MySQL? A:69 SELECT CURDATE();
CURRENT_DATE() = CURDATE()
for time use
SELECT CURTIME();
CURRENT_TIME() = CURTIME()     Q:70 What are the advantages and disadvantages of Cascading
Style
Sheets? A:70 External Style SheetsAdvantagesCan control styles for multiple documents at once.
Classes can be
created for use on multiple HTML element types in many documents.
Selector and grouping methods can be used to apply styles under complex
contextsDisadvantagesAn extra download is required to import style information for each
document The rendering of the document may be delayed until the external
style sheet is loaded Becomes slightly unwieldy for small quantities of
style definitionsEmbedded Style Sheets

Advantages

Classes can be created for use on multiple tag types in the document.
Selector and grouping methods can be used to apply styles under complex
contexts. No additional downloads necessary to receive style information

Disadvantages

This method can not control styles for multiple documents at once

Inline Styles

Advantages

Useful for small quantities of style definitions. Can override other


style specification methods at the local level so only exceptions need
to be listed in conjunction with other style methods

Disadvantages

Does not distance style information from content (a main goal of


SGML/HTML). Can not control styles for multiple documents at once.
Author can not create or control classes of elements to control multiple
element types within the document. Selector grouping methods can not be
used to create complex element addressing scenarios
    Q:71 What type of inheritance that PHP supports? A:71 In PHP an extended class is always
dependent on a single base class,
that is, multiple inheritance is not supported. Classes are extended
using the keyword ‘extends’.     Q:72 What is the difference between Primary Key and
Unique key? A:72 Primary Key: A column in a table whose values uniquely identify the
rows in the table. A primary key value cannot be NULL.

Unique Key: Unique Keys are used to uniquely identify each row in the
table. There can be one and only one row for each unique key value. So
NULL can be a unique key.There can be only one primary key for a table but there can be
more
than one unique for a table.

  
Q:73 The structure of table view buyers is as follows:

Field Type Null Key Default Extra

user_pri_id int(15)   PRI null auto_increment

userid varchar(10) YES   null  

the value of user_pri_id the last row 999 then What will happen in
the following conditions?

Condition1: Delete all the rows and insert another row then.
What is the starting value for this auto incremented field user_pri_id ,
Condition2: Delete the last row(having the field value 999) and
insert another row then. What is the value for this auto incremented
field user_pri_id

A:73 In both cases let the value for auto increment field be n then next
row will have value n+1 i.e. 1000     Q:74 What are the advantages/disadvantages of MySQL and
PHP? A:74 Both of them are open source software (so free of cost), support
cross platform. php is faster then ASP and JSP.     Q:75 What is the difference between GROUP BY
and ORDER BY in Sql? A:75 ORDER BY [col1],[col2],…,[coln]; Tels DBMS according to what columns
it should sort the result. If two rows will hawe the same value in col1
it will try to sort them according to col2 and so on.GROUP BY
[col1],[col2],…,[coln]; Tels DBMS to group results with same value of
column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if
you want to count all items in group, sum all values or view average     Q:76 What is the difference
between char and varchar data types? A:76 Set char to occupy n bytes and it will take n bytes even
if u r
storing a value of n-m bytes
Set varchar to occupy n bytes and it will take only the required space
and will not use the n bytes
eg. name char(15) will waste 10 bytes if we store ‘mizan’, if each char
takes a byte
eg. name varchar(15) will just use 5 bytes if we store ‘mizan’, if each
char takes a byte. rest 10 bytes will be free.     Q:77 What is the functionality of md5 function in
PHP? A:77 Calculate the md5 hash of a string. The hash is a 32-character
hexadecimal number. I use it to generate keys which I use to identify
users etc. If I add random no techniques to it the md5 generated now
will be totally different for the same string I am using.     Q:78 How can I load data from a text file
into a table? A:78 you can use LOAD DATA INFILE file_name; syntax to load data
from a text file. but you have to make sure thata) data is delimited
b) columns and data matched correctly     Q:79 How can we know the number of days between two
given dates using
MySQL? A:79 SELECT DATEDIFF(’2007-03-07′,’2005-01-01′);     Q:80 How can we know the number
of days between two given dates using
PHP? A:80 $date1 = date(‘Y-m-d’);
$date2 = ’2006-08-15′;
$days = (strtotime($date1) – strtotime($date2)) / (60 * 60 * 24);

Q:81 What is ‘float’ property in CSS?


A:81 The float property sets where an image or a text will appear in another element.    
Q:82 What is descendant structure in CSS?
A:82 Descendant selectors are used to select elements that are descendants of another
element in the document tree.For example, you may wish to target a specific <em>
element on the page, but not all <em> elements. A sample document could contain the
following code: <body>
<h1>Heading <em>here</em> </h1>
<p>Lorem ipsum dolor <em>sit</em> amet.</p>
</body> The document tree diagram (with the <em> element to be targeted) would be:

If you use a type selector like the example below, you will select all
<em> elements on the page:

em {color: blue; } However, if you use a descendant selector, you can refine the <em>
elements that you select. The rule below will only select <em> elements that are
descendants of <p> elements. If this rule is applied, the <em> element within the <h1>
will not be colored blue.

p em {color: blue; } You can also jump levels in the document tree structure to select
descendants. For example, the following code:

<body>
<p>Lorem ipsum dolor <em>sit</em> amet.</p>
<ul>
<li>item 1</li>
<li>item 2</li>
<li><em>item 3</em></li>
</ul>
</body> The document tree (with a third-level <em> element highlighted) would be:

Using the following rule you can isolate any <em> element inside a <ul> element,
without having to describe the <li> element. If this rule is applied, any <em> element
within a <ul> element will be colored blue. However, the <em> element within the <p>
will not be colored blue:

ul em {color: blue; } Descendant selectors are well supported across standards-


compliant browsers.

    Q:83 What is Child Descendant structure in CSS?


A:83

Child selectors

A child selector is used to select an element that is a direct child of another element
(parent). Child selectors will not select all descendants, only direct children.

For example, you may wish to target an <em> that is a direct child of a <div>, but not
other <em> elements that are descendants of the <div>. A sample document could
contain the following code:

<body>
<h1>Heading <em>text</em></h1>
<div>
This is some <em>text</em>
<p>This is a paragraph of <em>text</em></p>
</div>
</body>
The document tree (highlighting the <em> that is a child of the <div>) would be:
Using the following rule you can target any <em> element that is a child of the <div>.
Other <em> elements that are descendants but not direct children of the <div> will not
be targeted.

div > em { color: blue; }

OR

div>em { color: blue; }


Child selectors are not supported by Windows Internet Explorer 5, 5.5 and 6, but are
supported by most other standards-compliant browsers.

    Q:84 How to create a class in JavaScript? A:84 Classes can seem off-putting at first, but
once you see the point of them, their use can be invaluable.We have already met
objects. A computer object is a representation of a real object. For an estate agent the
object may be a house, including information about the number of rooms and the
price.An estate agent may have a lot of houses available. These houses all have different
characteristics, and as objects they all go through the same processes. They are viewed,
surveyed and bought, and so on.A full estate agent program would be difficult to
demonstrate here, but we can introduce the use of classes.In this example, we have the
house class. The house class produces house objects, all with object properties, such as
number of rooms and price, and all having access to the same methods, such as sold
and bought.

So a class can create objects with a group of properties and methods.

JavaScript doesn’t have a keyword specific to class, so we must go back to basics and
develop classes in a different way. This isn’t very difficult.

Class Properties

Let us examine a very small estate agent program.

<HTML>
<HEAD>
<TITLE>Estate Agent</TITLE>
<SCRIPT>
function House(rooms,price,garage) {
this.rooms=rooms;
this.price=price;
this.garage=garage;
}
house1=new House(4,100000,false);
house2=new House(5,200000,true);
with (house1) document.write(‘House 1 has ‘+rooms+’ rooms, ‘+(garage?’a':’no’)+’
garage, and costs £’+price+’<BR>’);
with (house2) document.write(‘House 2 has ‘+rooms+’ rooms, ‘+(garage?’a':’no’)+’
garage, and costs £’+price+’<BR>’);
</SCRIPT>
</HEAD>
</HTML>

We define a House function that takes three parameters, rooms, price and garage. The
function uses the this keyword to create an object.

When we call the House function, we assign the result to our variable, which becomes an
object.

So, identical code would be:

house1=new Object();
house1.rooms=4;
house1.price=100000;
house1.garage=false;

We would have to type this in for all houses, which would be very tedious and is why we
use the class structure instead.

When we display the details for a house, I have introduced the ternary operator, ‘?:’.
The ternary operator is a compacted version of:

if (garage) str=’a'; else str=’no’;

(garage?’a':’no’) means if garage is true, return ‘a’ else return ‘no’. Using the ternary
operator removes a line of code, and avoids having to create a new variable.

Class Methods

The House class we have so far defined only contains object properties. We could add a
method to replace the document.write() action we used before. (See example)

<HTML>
<HEAD>
<TITLE>Estate Agent 2</TITLE>
<SCRIPT>
function House(name,rooms,price,garage) {
this.name=name;
this.rooms=rooms;
this.price=price;
this.garage=garage;
this.view=view;
}
function view() {
with (this) document.write(name+’ has ‘+rooms+’ rooms, ‘+(garage?’a':’no’)+’ garage,
and costs £’+price+’<BR>’);
}
house1=new House(‘House 1′,4,100000,false);
house2=new House(‘Big House’,5,200000,true);
house1.view();
house2.view();
</SCRIPT>
</HEAD>
</HTML>

Much better!

Note how we must add another property, name, so that we can identify the house in
question. This offers more flexibility than re-using the variable name, and the variable
name is inaccessible anyway, i.e. it is very difficult, if not impossible, to get the view()
function to use the string ‘house1′.

    Q:85 Are namespaces are there in JavaScript?


A:81 A namespace is a container and allows you to bundle up all your functionality using
a unique name. In JavaScript, a namespace is really just an object that you’ve attached
all further methods, properties and objects. But it is not always necessary to use
namespace.     Q:86 What is JSON? What are the notations used in JSON? A:86 JSON
(JavaScript Object Notation) is a lightweight data-interchange format. It is easy for
humans to read and write. It is easy for machines to parse and generate. It is based on
a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition –
December 1999. JSON is a text format that is completely language independent but uses
conventions that are familiar to programmers of the C-family of languages, including C,
C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON
an ideal data-interchange language.     Q:87 How to get Query String in PHP for http request?
A:87 $_GET[] and $_REQUEST[]     Q:88 How to get the http Request in PHP? A:88 When
PHP is used on a Web server to handle a HTTP request, it converts information submitted
in the HTTP request as predefined variables:

 $_GET – Associate array of variables submitted with GET method.


 $_POST – Associate array of variables submitted with POST method.
 $_COOKIE – Associate array of variables submitted as cookies.
 $_REQUEST – Associate array of variables from $_GET, $_POST, and $_COOKIE.
 $_SERVER – Associate array of all information from the server and the HTTP
request.

    Q:89 How you provide security for PHP application?


A:89 There are many ways to accomplish the security tasks but the most common 7
ways are1. Validate Input. Never trust your user and always filter input before taking it
to any operation.2. Provide access control.3. Session ID protection4. preventing Cross
Site Scripting (XSS) flaws

5. SQL injection vulnerabilities.

6. Turning off error reporting and exposing to the site for hackers. Instead use log file to
catch exceptions

7. Effective Data handling

    Q:90 What is SQL Injection in PHP security?


A:90 SQL injection attacks are extremely simple to defend against, but many
applications are still vulnerable. Consider the following SQL statement:
<?php
$sql = "INSERT
INTO users (reg_username,
reg_password,
reg_email)
VALUES ('{$_POST['reg_username']}',
'$reg_password',
'{$_POST['reg_email']}')";
?>

This query is constructed with $_POST, which should immediately look suspicious.

Assume that this query is creating a new account. The user provides a desired username
and an email address. The registration application generates a temporary password and
emails it to the user to verify the email address. Imagine that the user enters the
following as a username:

bad_guy', 'mypass', ''), ('good_guy

This certainly doesn’t look like a valid username, but with no data filtering in place, the
application can’t tell. If a valid email address is given (shiflett@php.net, for example),
and 1234 is what the application generates for the password, the SQL statement
becomes the following:

<?php

$sql = "INSERT
INTO users (reg_username,
reg_password,
reg_email)
VALUES ('bad_guy', 'mypass', ''),
('good_guy',
'1234',
'shiflett@php.net')"; ?>

Rather than the intended action of creating a single account (good_guy) with a valid
email address, the application has been tricked into creating two accounts, and the user
supplied every detail of the bad_guy account.

While this particular example might not seem so harmful, it should be clear that worse
things could happen once an attacker can make modifications to your SQL statements.

For example, depending on the database you are using, it might be possible to send
multiple queries to the database server in a single call. Thus, a user can potentially
terminate the existing query with a semicolon and follow this with a query of the user’s
choosing.

MySQL, until recently, does not allow multiple queries, so this particular risk is mitigated.
Newer versions of MySQL allow multiple queries, but the corresponding PHP extension
(ext/mysqli) requires that you use a separate function if you want to send multiple
queries (mysqli_multi_query() instead of mysqli_query()). Only allowing a single
query is safer, because it limits what an attacker can potentially do.

Protecting against SQL injection is easy:


 Filter your data.This cannot be overstressed. With good data filtering in place,
most security concerns are mitigated, and some are practically eliminated.
 Quote your data.If your database allows it (MySQL does), put single quotes
around all values in your SQL statements, regardless of the data type.
 Escape your data.Sometimes valid data can unintentionally interfere with the
format of the SQL statement itself. Use mysql_escape_string() or an escaping
function native to your particular database. If there isn’t a specific one,
addslashes() is a good last resort.

    Q:91 What is cross site Scripting?


A:91 To understand what Cross Site Scripting is, let’s see a usual situation, common to
many sites. Let’s say we are taking some information passed in on a querystring (the
string after the (?) character within a URL), with the purpose of displaying the content of
a variable, for example, the visitor’s name:

http://www.yourdomain.com/welcomedir/welcomepage.php?name=John
As we can see in this simple querystring, we are passing the visitor’s name as a
parameter in the URL, and then displaying it on our “welcomepage.php” page with the
following PHP code:

<?php

echo ‘Welcome to our site ’ . stripslashes($_GET[‘name’]);

?>
The result of this snippet is shown below:

Welcome to our site John


This is pretty simple and straightforward. We’re displaying the content of the “name”
variable, by using the $_GET superglobal PHP array, as we have done probably hundreds
of times. Everything seems to be fine. Now, what’s wrong with this code? Nothing really.
But let’s modify the querystring by replacing our visitor’s name passed in the URL:

http://www.yourdomain.com/welcomedir/
welcomepage.php?name=John
with something like this:

http://www.yourdomain.com/welcomedir/
welcomepage.php?name=
<script language=javascript>alert
(‘Hey, you are going to be hijacked!’);</script>
Do you remember the PHP code included in our “welcome.php” page? Yes, you’re
correct. When we modify the querystring, the following code is executed:

<?php

echo ‘Welcome to our site ‘ .


<script language=javascript> alert(‘Hey, you are going
to be hijacked!’);</script>

?>
The output of this code is an alert JavaScript box telling you “Hey, you are going be
hijacked!” after the “Welcome to our site” phrase.
Very ugly stuff, right? That’s a simple example of the Cross Site Scripting vulnerability.
This means that any pasted JavaScript code into the URL will be executed happily with
no complaints at all.

    Q:92 Which method do you follow to get a record from a million records? (Searching, …. not
from database, from an array in php)
A:92 use array_search(), array_keys(), array_values(), array_key_exists(), and in_array().     Q:93
Which sorting method is lowest time consumable?
A:93 HeapSort, Merge sort are the lowest time consumable sorting algorithm.

  
Q:94 Which sorting method is lowest memory consumable?
A:94

What are the advantages of Mysql comparing with oracle?


How we can count duplicate entery in particular table against Primary Key ? What are constraints?
How to connect mysql from jsp(Java Server Page)?
How to display nth highest record in a table for example?How to display 4th highest (salary) record from customer
table?
How do you change a password for an existing user via mysqladmin?
Which version of MySQL supports Subquery?
Describe the use of %ROWTYPE and %TYPE in PL/SQL
What is SERIAL data type in MySQL?
What does "tee" command do in MySQL?
What?s the default port for MySQL Server?
Explain federated tables
How do you start and stop MySQL on Windows?
How do you start MySQL on Linux?
Use mysqldump to create a copy of the database?
What are some good ideas regarding user security in MySQL?
Explain the difference between MyISAM Static and MyISAM Dynamic
What are HEAP tables in MySQL?
How do you control the max size of a HEAP table?
How do you configure mysql on linux
How to see the database architecture in MySQL??
What packages (if any) has Oracle provided for use by developers?
Describe the use of PL/SQL tables
How do you start and stop MySQL on Windows?
Explain about the rules which should be followed while assigning a username?
What does myisamchk do?
What are CSV tables?
State some of the disadvantages present in MYSQL?
When is a declare statement needed ?
How to create MYSQL new users?
State some of the features of MYSQL?
Explain about primary keys?
Explain about normalization?
What happens when the column is set to AUTO INCREMENT and you reach the maximum value for that
table?
Explain about MYSQL and its features?
Explain about database design?
Explain about creating database?
State two considerations which can improve the performance of MYSQL?
Explain about the time stamp field?
Explain about HEAP table?
Explain about MyISAM table?

what is difference between candidate key and primary key


Can you save your connection settings to a conf file?
Explain some of the uses of MYSQL?
Explain the difference between mysql and mysqli interfaces in PHP?
What happens when we don?t use Console option?
Explain about a security flaw which is present while creating a username?
State some security recommendations while using MYSQL?
Explain the difference between BOOL, TINYINT and BIT.
What happens if a table has one column defined as TIMESTAMP?
Explain data type TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
What does TIMESTAMP ON UPDATE CURRENT_TIMESTAMP data type do?
How do you use Outer Join in MySQL
What is the Oracle rowid counterpart in MySQL?
How will retrieve nth level categories from one query in mysql ?
What are the advantages of mysql comparing with oracle?
What are the limitations of mysql in Comparison of Oracle?
How many drivers in MYSQL?

What's foreign data in php?


* Anything from a form* Anything from $_GET, $_POST, $_REQUEST* Cookies
($_COOKIES)* Web services data* Files* Some server variables (e.g.
$_SERVER['SERVER_NAME'])* Environment variables* Database query results Filter
supports get, post, cookies, server and environment variables as well as defined variables
(server support may not work in all sapi, for filter 0.11.0 or php 5.2.0). ....!
what is Memcache?
Memcache is a technology which caches objects in memory where your web application can
get to them really fast. It is used by sites such as Digg.com, Facebook.com and
NowPublic.com and is widely recognized as an essential ingredient in scaling any LAMP
application to handle enormous traffic.   ....!
what is database testing and what we test in database testing?
Database testing basically include the following. 1)Data validity testing. 2)Data Integritity
testing 3)Performance related to data base. 4)Testing of Procedure,triggers and functions. for
doing data validity testing you should be good in SQL queries For data integrity testing you
should know about referintial integrity and different constraint. For performance related
things you should have idea about the table structure and design. for testing Procedure
triggers and functions you should be able to understand the sam....!
Will persistent connection work in the CGI version of php ? mysql_connect() vs
mysql_pconnect()?
Persistent database connections work only in the module installation of PHP. If you ask for a
persistent connection in the CGI version, you will simply get a regular connection. if you
become convinced that the sheer overhead of opening new database connections is killing
your performance, you might want to investigate opening persistent connections.Unlike
regular database connections, these connections are not automatically killed when your page
exits (or even when mysql_close() is called) but are saved ....!
What is Model-view-controller (MVC)?
Model-view-controller (MVC) is a design pattern used in software engineering. In complex
computer applications that present lots of data to the user, one often wishes to separate data
(model) and user interface (view) concerns, so that changes to the user interface do not
impact the data handling, and that the data can be reorganized without changing the user
interface. The model-view-controller design pattern solves this problem by decoupling data
access and business logic from data presentation and user interaction, by introducing an
intermediate....!
What is the difference between CHAR and VARCHAR data types?
Ans: CHAR is a fixed length data type. CHAR(n) will take n characters of storage even if
you enter less than n characters to that column. For example, "answers" will be stored as
"answers " in CHAR(10) column. VARCHAR is a variable length data type. VARCHAR(n)
will take only the required storage for the actual number of characters entered to that column.
For example, "answers" will be stored as "answers&q....!
Installing PHP on your Computer?
You can download apache2triad from http://sourceforge.net/projects/apache2triad/ Its a
single setup file for --------------------------- Apache2 , MySQL , PostgreSQL , OpenSSL ,
Xmail , SlimFTPd Software developing triad of : PHP , Perl and Python + Apache2TriadCP ,
PHPmyadmin , PHPPgAdmin , AWStats , UebiMiau , PHPXMail , PHPSFTPd. All latest
stables , all manuals Use t....!
what is the output of below script?
<?php $x = 3; switch ($x) { case 2: echo 'line 1'; break; case 3: case 4: echo 'line 2'; break;
default: echo 'line 3'; } ?> a. echo 'line 3'; b. echo 'line 2'; c. Error d. None of the above Ans:
b (Answer is line2) www.w3answers.com ....!
How we can pass data from PHP to ASP,ASP.net?
PHP to ASP Let's first look at how you can pass data from PHP to ASP using WDDX. You
create a WDDX packet by first serializing data into a WDDX packet and then presenting it.
WDDX can convert most variable types that applications use, such as strings, integers, and
arrays. After a variable has been converted to a WDDX variable type, it is ready for another
application to pick up. PHP has WDDX support built in, so you don't need to modify your
PHP.ini file to start using WDDX. A ....!
what is the use of –i-am-a-dummy flag in MySql?
It Makes the MySQL engine refuse UPDATE and DELETE commands where the WHERE
clause is not present. ....!
What is the difference between GET and POST methods in form submitting? Give the cases
where we can use GET and POST methods?
The main difference between GET and POST is how the form data is passing. Both are used
for passing form field values. All the values which is submitted by the GET method will be
appended to the URL.Where as POST method send the data with out appending the
URL(hidden) In GET Method we can bookmark the URLs where as in POST method its not
possible In GET Method there is a limit for passing the data from one page to another(ie 256
characters according to w3c standards)But in POST we can send large amount of data
How does Database handle Sessions?
As you should be aware the HTTP protocol, as used for serving web pages, is completely
stateless. This means that after the server has received a request, processed it and sent a
response, the process which dealt with that request dies. Anything that the process had in its
memory therefore dies with it, so when a subsequent request is received from the same client
it is unable to refer to its memory about anything that happened previously. Fortunately PHP
provides a standard method of maintaining memory (state) between ....!
Which of the following functions is most efficient for substituting fixed patterns in strings?
A. preg_replace() B. str_replace() C. str_ireplace() D. substr_replace() Answer B is correct.
The PHP efficiency mantra is “do no more work than necessary.” Both str_ireplace() and
preg_replace() have more expensive (and flexible) matching logic, so you should only use
them when your problem requires it. substr_replace() requires you to know the offsets and
lengths of the substrings you want to replace, and is not sufficient to handle the t....!
what is the output below mentioned ?
<? $string = 'APPLE'; echo stristr($string, 97); ?> a) Error b) APPLE c) Apple d) None of the
above ANS : APPLE ....!
Your first PHP script - "Hello World"
<?php echo 'Hello World'; ?> ....!

<?php echo 'Hello World'; ?>

MySQL Interview Questions


1) Explain about MYSQL and its features?
MYSQL is a relational data base model and most widely RDBMS all over the world. It
provides multi user access to databases. Source code for this database is available under
General public license. It became popular for web applications and this is widely used.
Performance and reliability became its features.

2) Explain some of the uses of MYSQL?


MYSQL is widely used for web applications. This acts as a database component for many
languages such as BAMP, WAMP, LAMP and MAMP. PHP and ruby added to popularity to
the language. PHP and MYSQL are very much used for managing database and web
applications.

3) State some of the features of MYSQL?


Some of the features presented by MYSQL are
1) Multiple storage engines, Native storage engines, Partner developed storage engines,
custom storage engines, community developed storage engines and commit grouping.
Some of these features present in MYSQL are not present in most popular RDBMS.

4) State some of the disadvantages present in MYSQL?


MYSQL standard has diverted on the standards of implementation of Null and default values.
Arithmetic operations are susceptible to integer over flow. Mode of operation of SQL is set to
unusual tolerant state which developers hate.

5) What happens when we don’t use Console option?


If console option is not present or used during the start of MYSQL then all the output will be
written to the error log file. It is always better to use the console option because it reduces
problem on the server. Error log file will be stored with an extension .err. Any text editor can
read this file.

6) How to create MYSQL new users?


There are many different ways to establish users and privileges in MYSQL. Client and
GRANT command assure you about a safe connection. The syntax for establishing new users
and privileges is as follows
GRANT privileges ON database.* TO
‘username’@’hostname’ This can be identified by the password. Privileges can be assigned
one by one or by specifying all.

7) Explain about the rules which should be followed while assigning a username?
A username has a maximum length of 16 characters. Spaces should be avoided while creating
username because they are case sensitive. Hostname will be the computer from which you are
going to connect. The best way to specify a username is to connect through a local host.

8) Explain about a security flaw which is present while creating a username?


Naming MYSQL databases has to be very careful because any database starting with the test
name can be accessed by every one on the network. Make sure that you don’t start the
databases naming with test. It should be used only for experimental purposes only.

9) State some security recommendations while using MYSQL?


Some of the security recommendations which should be followed while using MYSQL are as
follows: -
1) Minimal privileges to users in the network.
2) Super and process privileges should be granted minimally.
3) File privileges should be granted minimally to administrators.
4) Validation of data and queries should be thoroughly checked.

10) Explain about database design?


Database design is also called as Data modeling. It is used for long-term management of
database. This process is used to store information and to keep data for long term. Creating an
efficient structure helps you to channelize information into good channels.
11) Explain about creating database?
CREATE DATABASE command will create you a database with the assigned name by the
user. This is an optional statement but when you actually assign a name it checks for
similarity and gives error if it encounters one. CREATE DATABASE models help you to
create classic models.

12) Explain about primary keys?


MYSQL allows only one primary key. This primary key can be used on multiple tables.
There are many rules which should be followed such as it shouldn’t be null and it can never
change. Primary key assigned should be unique it cannot be matched with any other keys.

13) Explain about normalization?


Applying specific rules (normal forms) to the database is the primary process. These rules
should be applied in the order specified starting with the first normal form. These rules
should be adhered by every database they are
1) Each column should have only one value
2) Repeating columns of data cannot be done.

14) State two considerations which can improve the performance of MYSQL?
Two considerations which can improve the performance of MYSQL are as follows: -
1) Fixed length fields take up more space than variable length fields but they are a bit faster.
2) Size of the field should be restricted to the smallest possible value based upon the largest
input value.

15) Explain about the time stamp field?


TIMESTAMP filed occurs when an INSERT and UPDATE field occurs when there is no
value specified for the field. There are many behaviors for TIMESTAMP field and it depends
upon the version of MYSQL.

16) Explain about MyISAM table?


This feature is a default type for tables. This table is not so much considered for transactions
because it is not considered as safe but this kind of table is very fast in execution. The
maximum key length is 1024 bytes and 64 keys per table. Size of this table entirely depends
upon the operating system.

17) Explain about HEAP table?


This type of table is stored in the memory. Speed of execution of this table is very
commendable. There are associated disadvantages associated with this table the primary one
being loss of stored memory which occurs when there is power failure and can cause the
server to run out of memory. Columns with AUTO_INCREMENT, TEXT characteristics and
BLOB are not supported.

1. What are the differences between Get and post methods in form submitting, give the case where
we can use get and we can use post methods?
2. Who is the father of php and explain the changes in php versions?
3. How can we submit from without a submit button?
4. How many ways we can retrieve the date in result set of mysql using php?
5. What is the difference between mysql_fetch_object and mysql_fetch_array?
6. What is the difference between $message and $$message?
7. How can we extract string 'abc.com ' from a string 'http://info@abc.com' using regular
_expression of php?
8. How can we create a database using php and mysql?
9. What are the differences between require and include, include_once?
10. Can we use include ("abc.php") two times in a php page "makeit.php"?

You might also like