PHP:TheUltimate
StepbyStepguideforbeginnerson
howtolearnPHPandMYSQL
programminginjust6hours
ByEmilyGoldstein
©Copyright2015byWECANTBEBEATLLC
TableofContents
INTRODUCTION
CHAPTER1:SETTINGUPYOURSERVER
0.1CreatingthepublicHTMLPages
0.2Creatingthedatabaseandit’stables
0.3Addinguserstothedatabase
0.4Userlog-in:Authentication
CHAPTER2:SETTINGUPTHEHOMEPAGEFORLOGGED-INUSERSAND
LOGGING-OUT
2.1TestingPageSecurity
2.2Addingdatatothelist-UserAccessOnly
CHAPTER3:DISPLAYINGDATAINTHEHOMEPAGE
3.1EditingData
3.2Deletingdata
3.3Displayingpublicdata
CHAPTER4:DYNAMICCONTENTANDTHEWEB
4.1HTTPandtheInternet
4.2PHPandMySQL’sPlaceinWebDevelopment
4.3TheComponentsofaPHPApplication
4.4IntegratingManySourcesofInformation
4.5RequestingDatafromaWebPage
CHAPTER5:EXPLORINGPHP
5.1PHPandHTMLText
5.2CodingBuildingBlocks
CHAPTER6:PHPDECISION-MAKING
6.1Expressions
6.2OperatorConcepts
6.3BreakingOut
6.4Looping
CHAPTER7:FUNCTIONS
7.1CallingFunctions
7.2DefiningFunctions
7.3Object-OrientedProgramming
CHAPTER8:ARRAYS
8.1ArrayFundamentals
CHAPTER9:WORKINGWITHMYSQL
9.1MySQLDatabase
9.2ManagingtheDatabase
9.3UsingphpMyAdmin
9.4DatabaseConcepts
9.5StructuredQueryLanguage
CHAPTER10:DATABASEBESTPRACTICES
10.1DatabaseDesign
10.2BackingUpandRestoringData
10.3AdvancedSQL
CHAPTER11:GETTINGPHPTOTALKTOMYSQL
11.1Theprocess
11.2QueryingtheDatabasewithPHPFunctions
CHAPTER12:WORKINGWITHFORMS
12.1BuildingaForm
12.2Templates
CHAPTER13:PRACTICALPHP
13.1StringFunctions
13.2Dateandtimefunctions
13.3FileManipulation
13.4CallingSystemCalls
CHAPTER14:XHTML
14.1WhyXHTML?
14.2XHTMLandXMLNamespaces
14.3XHTMLVersions
14.4CreatingXHTMLwithPHP
CHAPTER15:MODIFYINGMYSQLOBJECTSANDPHPDATA
15.1ChangingDatabaseObjectsfromPHP
15.2ManipulatingTableData
15.3ManipulatingTableData
INTRODUCTION
Areyouinspiredbytheideaofmakingyourownwebsite?Everthoughtabouthow
coolisittohaveawebsitethathasalog-in/log-outfunctionality?Needtofigure
outhowtoCreate,Read,UpdateorDelete(CRUD)recordsinadatabase?Have
youlosttrackofyourpastinstructionalexercises?Havingconsideredallthese
questions,I’mgoingtoshowyouhowtomakeawebsitewithoutanyoutsidehelp
whereyouwillknoweachandeverysubtleelementonhowthePHPwebsitecode
functions.Ifyouarenewtoback-endwebdevelopment,thisinstructionalbookis
foryou.
I’llclarifyeverythinginyourpointofinterestsothatyouwon’tneedtoresearch
somespecifictechniquesbeingusedinPHP.Tokeepthingsasstraightforwardas
possible,wewon’tbeusinganycomplexsystems.Additionally,Iwon’tbe
concentratingonthewebsitesdesignbecauseweareafterthefunctionalities.
However,it’sanythingbutdifficulttoexecutethedesign.Whatthisbookwillbe
doingisaneasyyetexhaustiveanalysisoftheentirePHPCodingprocess.
So,whatisPHP?Intheeventthatyouownasiteorneedasitedesigned,youmay
needtoknowtheresponsetothisquestion.Consider-in1999itwasassessed
thereweremorethan100,000sitesutilizingPHPtoupgradetheirownparticular
site.Today,therearemorethan1,000,000sitesutilizingPHP.
PHPisaprevalentandbroadlyutilizedprogrammingdialectutilizedforsite
improvement.PHPstandsforPHP:HypertextPreprocessor.
IntheearlyyearsoftheInternet,mostdestinationswerestaticcontentpages.As
theInternetadvanced,individualsneededsiteswithmoreintuitivefunctionality,
forexample,visitorbooksandcontactframes.PHPwastheidealinstrumentand
stillistoday.
PHPisanexceptionallystrongandexperiencedprogrammingdialect.Itwas
initiallyreleasedin1995andhasdevelopedtoturnintooneofthefavoreddialects
forsiteadvancement.Itrunsontheserversideandisexceptionallysecure.Now
thatit’soutintheopen,mostfacilitatingorganizationsgivePHPtheirfacilitating
bundles.
Intheeventthatyourequireaninteractivesite,withcomponentslikevisitor
booksandcontactshapes,youcanlearnPHPprogrammingyourself,purchasea
sitebundle,orcontractaProfessionalPHPProgrammer.Agreatnumberof
peopledon’thaveroom,scheduleorcapabilitytotakeinaprogrammingdialect
e.g.PHPandchoosetoacquiresitepacks.Onerecentmyrecentcustomers
acquiredado-it-withoutanyoneelse’shelpsitepackfromavastre-sell.These
packs,howeverofferfundamentalsitesthatcanworkforafewindividuals,have
littlefunctionalityandofferrestrictedhighlights.Inthewakeofbattlingwithit,
thiscustomeremployedmetodevelophissite.Afterfinishingit,henowhasasite
thatislovelyandhasincrediblefunctionalityandinteractiveelementsthathis
customersneed.Hissiteisalongwaypastwhatasitepackcouldhaveevergiven.
ThisisthedistinctionofPHP!
CHAPTER1:SETTINGUPYOURSERVER
Sincenowyouhaveeverythingsetandreadytogo,asthenutsandboltsof
programminggoes,weshouldbeginbymakingabasicshoutoutof“hiworld”in
theserver.
Tostartwith,gotothecatalogwhereyouintroducedyourXAMPP(Commonlyin
C:\xampp).Fromthatpoint,gotothehtdocsenvelope(Commonlyin
C:\xampp\htdocs)andmakeanorganizernamed“MyFirstWebsite”.
Fromthatpart,youhavenowmadeaLocalURLforyourwebsite.Thatenvelope
willbeutilizedtosupplyinallwebsiterecords(.html,.php,.css,.js,andsoforth.).
Openupyourcontentmanagerandnowwecanbegin!
Iutilizesuperbcontentasmywordprocessor.Ontheoffchancethatyou’re
utilizingNotepad++oranyotherprocessors,it’salright.It’snotsomuchofa
majorcomponentyetbecauseit’sonlyaninclinationonwhichoneyoumight
wanttoutilize.
WhatwewilldoisafundamentalHTMLpageandpresentation“hiworld”from
theserver,utilizinganessentialPHPlanguagestructure.Wewillthensortthe
accompanyinggrammar:
ABOVECODING:
<html>
<head>
<title>MyfirstPHPWebsite</title>
</head>
<body>
echo“
HelloWorld!
”;
?>
</body>
</html>
Savethedocumenttothe“MyFirstWebSite”Folderandnameitas“index.php”.
(Indexasseenonthetopbarofthepicture)
Giventhatyouhavetherecord,weshouldnowopenyourXAMPPcontrolboard.
Intheeventthatitdoesn’tshowuponyourdesktop,itissituatedinyourXAMPP
envelopeasseenonthepicture:
Nowthatit’sthere,RunyourApacheandmySQLbytappingthe“Begin”catchon
theactivitiessegment.YououghttoseeanirregularPID(s)andthedefaultport
number.Apacheisthenameofourwebserverinwhichitwillhandleeveryone
ofthedocumentsandalsoserveasthecorrespondencetothewebprogramand
MySQLisourdatabasewhichwillstorethegreaterpartofourdata.
Openupyourwebprogramandinthelocationbar,clicklocalhost.Yououghtto
seethemenuofyourXAMPP.
Ontheoffchancethatit’sthefirsttimewhenyourunit,itwillaskwhatdialect
youwouldinclinetoward,justbasicallypickoneanditwillleadyoutothemenu.
Ontheoffchancethatyouwillseetheindexislocalhost/xampp,it’stheplacethe
defaultpagedrivesyouregardlessofthewhetheryouwriteinlocalhost.
OntheoffchancethatyouwillseethattheURLisMyFirstWebsite,itisgotten
fromthehtdocsorganizeranditnaturallyperusesdocumentsthatarenamed
“index”(Beitindex.html,index.aspx,andsoon),whichservesasthedefaultpage.
Nonetheless,writinglocalhost/MyfirstWebsite/index.phpisimportant.Youcan
alsomakeyourcustomnamefortheURLbyessentiallyrenamingtheorganizer
buthowaboutwesimplysticktoMyFirstWebsitefornow.
Note:Ifyoudon’thavearecordnamedlistandyouentertheURL,youwillgeta
slip404fornothavingthedocumentontheserver.Incaseyoudohavedistinctive
documentsthatarenotnamedindex<extention>,youneedtodeterminethe
particularrecordname.E.g:localhost/MyfirstWebsite/page.php.
0.1CreatingthepublicHTMLPages
Thenextstepisthatweshouldchangeourwebsiteandincludearegistrationpage
whereourclientscanenrollandalsoaLog-inpageimmediatelyaftergetting
enlisted.Weshouldalsoadjustourlandingpagewiththeaccompanyingcode:
CODEABOVE:
<html>
<head>
<title>MyfirstPHPWebsite</title>
</head>
<body>
echo“
HelloWorld!
”;
?>
<ahref=”login.php”>Clickheretologin
<ahref=”register.php”>Clickheretoregister
</body>
</html>
Itshouldbeobviousbynowthatwehavejustincluded2connectionswhichare
fortheLoginandregister.Weshouldmaketheregistrationpagefirst.Asyoucan
see,it’sonlyanessentialstructurewheretheclientcanincludehis/her
accreditations.Fortheloginpage,insertthiscode:
Insight:Justduplicatethesamecodetomakethingseasierandfaster.
login.php
CODEABOVE:
<html>
<head>
<title>MyfirstPHPWebsite</title>
</head>
<body>
LoginPage
<ahref=”index.php”>Clickheretogoback
<formaction=”checklogin.php”method=”POST”>
EnterUsername:<inputtype=”text”name=”username”required=”required”/>
Enterpassword:
/>
<inputtype=”submit”value=”Login”/>
</form>
</body>
</html>
Fundamentally,it’sstillthesamecodeasfromtheregister.phpbutthe
adjustments/progressionsmadeweretheonesunderlined.
Tryrunninglocalhost/MyFirstWebsiteagainandyourpagesoughttoappearlike
this:
index.php
login.php
register.php
0.2Creatingthedatabaseandit’stables
Nowthathaveourmostimportantpageforallpeopleingeneral,howaboutwe
continuetothedatabase?
Tostartwith,selectlocalhost/phpmyadmin.Thiswillleadyoutothe
phpmyadminlandingpage:
Localhost/phpmyadmin
Fromthatpoint,gototheDatabasestabsituatedontopthenfromthecontentbox
inthecenter,selectfirst_dbthentaponmake.SimplyleavetheCollationas
shownbelow:
Youhavenoweffectivelymadeyourfirstdatabase.
Fromthatpoint,howaboutwemakeatableinwhichwecanenrollourclientsand
showcasedata?Tostartwith,clickonfirst_dbsituatedontheleftsideandmakea
tablenamedclientswith3segmentsthentaponGo.
Forthetable’sstructure,choosetohavetheaccompanyingfieldsthentapon
recovery:
Group:ColumnName-Type-Length-NullProperty-OtherProperties
Id-INT-N/A-NotNull-AutoIncrement
Username-varchar-50-Notnull
Secretkey-varchar-50-Notnull
Leaveeverythingasdefaultifitisnotdetermined.
Note:Youhavetosrolltotherightofthatpagefortheauto_increment.Isimply
alteredthephototofittheA_Ifield
Next,makeanothertablenamedrundownwith7sectionsandforthetable’s
structure:
id-INT-N/A-NotNull-AutoIncrement
pointsofinterest-content-Notnull
date_posted-varchar-30-Notnull
time_posted-Time-Notnull
date_edited-varchar-30-Notnull
time_edited-Time-Notnull
open-varchar-5-Notnull
0.3Addinguserstothedatabase
Sincewehaveourtables,weshouldproceedtothefunpart,gettingyour
enlistmentpageusable.Fromyourregistration.php,includethehtmlcodesaddonbelow:
register.php
Here’stheamplificationtothecode:
<html>
<head>
<title>MyfirstPHPWebsite</title>
</head>
<body>
RegistrationPage
<ahref=”index.php”>Clickheretogoback
<formaction=”checklogin.php”method=”POST”>
EnterUsername:<inputtype=”text”name=”username”required=”required”/>
Enterpassword:
/>
<inputtype=”submit”value=”Register”/>
</form>
</body>
</html>
$_SERVER[“REQUEST_METHOD”]==“POST”-checksifthestructurehas
gottenaPOSTmethodwhenthesubmitbuttonhasbeenclicked.ThePOST
methodismadeinhtmlfromthemethod=”POST.
$_POST[‘’]-getsthenameoriginatingfromaPOSTmethod.Thisactionbasically
getstheinfowithregardstothenamefromthestructure.Foroursituationit’s
usernameandpassword.
mysql_real_escape_string()-exemplifiestheinformationintoastringtokeep
inputsfromSQLInjections.Thisguaranteesthatyourstringsdon’tescapefrom
extracharacters.
Afterthat,gotoyourregister.phpandattempttoinputanydatathenclickon
“Register”.FormysituationIputintheusernamextianandpasswordas123456.
Itoughttoshowtheinputsbelow.Here’smyspecimen:
Throughthispartyououghttohaveseenonthemostproficientmethodtoget
infothroughthestructureandhowtoaddittothedatabase.Onyourregister.php,
includethesupplementarycode:
Herearetheclarificationstothecode:
<html>
<head>
<title>MyfirstPHPWebsite</title>
</head>
<body>
RegistrationPage
<ahref=”index.php”>Clickheretogoback
<formaction=”checklogin.php”method=”POST”>
EnterUsername:<inputtype=”text”name=”username”required=”required”/>
Enterpassword:
/>
<inputtype=”submit”value=”Register”/>
</form>
</body>
</html>
alert(“Usernamehasbeentaken!”);</script>’;//Promptstheuser
Print‘<script>window.location.assign(“register.php”);</script>’;//redirectsto
register.php
}
}
if($bool)
{
mysql_query(“INSERTINTOusers(username,password)VALUES(‘$username’,
‘password’)”);//insertsvalueintotableusers
Print‘<script>alert(“SuccessfullyRegistered!”);</script>’;//Promptstheuser
Print‘<script>window.location.assign(“register.php”);</script>’;//redirectsto
register.php
}
}
?>
mysql_connect(“Servername”,”ServerUsername”,”ServerPassword”)-The
sentencestructureusedtojoinwithourXAMPPserver.localhostor127.0.0.1is
thenameoftheserver.Thedefaultusernameisrootandnosecretwordfor
default.
mysql_select_db(“databasename”)-Selectsthedatabasetobeutilized.
thenagaindie(‘Message’)-Displaysthelapsemessageiftheconditionwasn’tmet.
mysql_query(‘sqlquestion’)-doestheSQLinquiries.
mysql_fetch_array(‘query’)-bringsallquestionsinthetabletoshoworcontrol
data.Itisputinaasacirclesothatitwouldquestionallcolumns.Observethat,
just1lineisquestionedpercirclethatisthereasonawhilecircleisvital.
$row[‘rowname’]-theestimationofthesectioninthepresentinquiry.Itis
representedasanexhibit.Foroursituation$rowisthenameofthevariablefor
ourcolumnontheupanddown.
Attempttheinputsthatyouhavemadebeforeandseewhathappens.Itoughtto
showthatyouhaveeffectivelyregistered.Attemptgoingtophpmyadminandsee
yourclientstable:
Congrats!Nowyouknowhowtoincludedataintothedatabasewithdata
validations.
0.4Userlog-in:Authentication
Subsequently,fortheloginpage,weshouldmakeanotherdocumentcalled
checklogin.php.Thereasonisbacktrackingtoourlogin.php,ourstructurehasan
activitycalled“checklogin.php”,especially
method=“POST”>.Intheeventthatyouwillseeitontheregister.php,it’salsoon
register.phpbecausetheback-endisdoneonthesamedocumenttoo.
Howaboutwenowcodethechecklogin.phpwiththeaccompanyinglanguage:
checklogin.php
session_start();
$username=mysql_real_escape_string($_POST[‘username’]);
$password=mysql_real_escape_string($_POST[‘password’]);
$bool=true;
mysql_connect(“localhost”,“root”,“”)ordie(mysql_error());//Connecttoserver
mysql_select_db(“first_db”)ordie(“Cannotconnecttodatabase”);//Connectto
database
$query=mysql_query(“Select*fromusersWHEREusername=’$username’”);//
Querytheuserstable
$exists=mysql_num_rows($query);//Checksifusernameexists
$table_users=“”:
$table_password=“”;
if($exists>0)//IFtherearenoreturningrowsornoexistingusername
{
while($row=mysql_fetch_assoc($query))//displayallrowsfromquery
{
$table_users=$row[‘username’];//thefirstusernamerowispassedonto
$table_users,andsoonuntilthequeryisfinished
$table_password=$row[‘password’];//thefirstpasswordrowispassedonto
$table_password,andsoonuntilthequeryisfinished
}
if(($username==$table_users)&&($password==$table_password))//checks
ifthereareanymatchingfields
{
if($password==$table_password)
{
$_SESSION[‘user’]=$username;//settheusernameinasession.Thisservesasa
globalvariable
header(“location:home.php”);//redirectstheusertotheauthenticatedhome
page
}
}
else
{
Print‘<script>alert(“IncorrectPassword!”);</script>’;//Promptstheuser
Print‘<script>window.location.assign(“login.php”);</script>’;//redirectsto
login.php
}
}
else
{
Print‘<script>alert(“Incorrectusername!”);</script>’;//Promptstheuser
Print‘<script>window.location.assign(“login.php”);</script>’;//redirectsto
login.php
}
?>
session_start()-Startsthesession.Thisisnormallydoneonestablishedpages.
Thereasonwhyweusedthisisbecauseitisneededforthe$_SESSION[‘’].
mysql_num_rows()-Thisyieldsawholenumber.Thisnumberseveryoneofthe
columnsdependingontheinquiry.
$_SESSION[‘name’]-Servesasthesessionnameforthewholesession.Thisis
moreorlesslikeopenvariablesinitemarrangedprogramming.Wewillbe
utilizingthisforrecognizingwhethertheclientisvalidatedornot.
Thenattempttotestyourdatawithawrongusernameandpassword.Itoughtto
givebackthepreferredprompt.Aftertesting,tryinputtingtherightvalues.It
oughttoleadyoutohome.php.
Note:home.phpdoesnotexistyetsoitwillcreateanerror404.
CHAPTER2:SETTINGUPTHEHOME
PAGEFORLOGGED-INUSERSAND
LOGGING-OUT
Nowthatwereconfirmed,letnowmakeourlandingpage(home.php)withthe
accompanyingsyntax:
home.php
CODEABOVE:
<html>
<head>
<title>MyfirstPHPWebsite</title>
</head>
session_start();//startsthesession
if($_SESSION[‘user’]){//checksiftheuserisloggedin
}
else{
header(“location:index.php”);//redirectsifuserisnotloggedin
}
$user=$_SESSION[‘user’];//assignsuservalue
?>
<body>
HomePage
<hello>!
<!—Display’susername—>
<ahref=”logout.php”>Clickheretogologout</a>
<formaction=”add.php”method=”POST”>
Addmoretolist:<inputtype=”text”name=”details”/>
Publicpost?<inputtype=”checkbox”name=”public[]”value=”yes”/>
<inputtype=”submit”value=”Addtolist”/>
</form>
Mylist
Id Details Edit Delete
</body></html>
Here’stheexplanationtothecode:
session_start()-Basicallystartsthesession.Requiredfor$_SESSION[‘’].
header()-redirectstheuser.
Tryrefreshingyourbrowseranditshouldlooklikethis:
Nowthatwehaveourhomepage,let’strycreatingourlogout.phpandtestifthe
user’ssessionisoff.Whatwewillensureisthatiftheuserislogged-out,theuser
shouldn’taccesshome.php.Sohere’sthesimplesyntaxtologout.php:
logout.php