Download - Cara Pembuatan PHP Dasar
-
8/10/2019 Cara Pembuatan PHP Dasar
1/101
PHP Tutorial
W3Schools Home Next Chapter
PHP is a powerful tool for making dnamic andinteracti!e We" pages#
PHP is the widel$used% free% and efficient alternati!eto competitors such as &icrosoft's (SP#
)n our PHP tutorial ou will learn a"out PHP% and howto execute scripts on our ser!er#
Start learning PHP now!
PHP *ui+ Test
Test our PHP skills at W3Schools,
Start PHP *ui+,
PHP -eferences
(t W3Schools ou will find complete references of all PHP functions.
(rra functions Calendar functions /ate functions /irector functions 0rror functions 1ilesstem functions 1ilter functions 1TP functions HTTP functions 2i"&2 functions &ail functions &ath functions &isc functions &S*2 functions Simple&2 functions String functions &2 Parser functions 4ip functions
http://www.w3schools.com/default.asphttp://www.w3schools.com/php/php_intro.asphttp://www.w3schools.com/php/php_intro.asphttp://www.w3schools.com/php/php_quiz.asphttp://www.w3schools.com/php/php_ref_array.asphttp://www.w3schools.com/php/php_ref_calendar.asphttp://www.w3schools.com/php/php_ref_date.asphttp://www.w3schools.com/php/php_ref_directory.asphttp://www.w3schools.com/php/php_ref_error.asphttp://www.w3schools.com/php/php_ref_filesystem.asphttp://www.w3schools.com/php/php_ref_filter.asphttp://www.w3schools.com/php/php_ref_ftp.asphttp://www.w3schools.com/php/php_ref_http.asphttp://www.w3schools.com/php/php_ref_libxml.asphttp://www.w3schools.com/php/php_ref_mail.asphttp://www.w3schools.com/php/php_ref_math.asphttp://www.w3schools.com/php/php_ref_misc.asphttp://www.w3schools.com/php/php_ref_mysql.asphttp://www.w3schools.com/php/php_ref_simplexml.asphttp://www.w3schools.com/php/php_ref_string.asphttp://www.w3schools.com/php/php_ref_xml.asphttp://www.w3schools.com/php/php_ref_zip.asphttp://www.w3schools.com/default.asphttp://www.w3schools.com/php/php_intro.asphttp://www.w3schools.com/php/php_intro.asphttp://www.w3schools.com/php/php_quiz.asphttp://www.w3schools.com/php/php_ref_array.asphttp://www.w3schools.com/php/php_ref_calendar.asphttp://www.w3schools.com/php/php_ref_date.asphttp://www.w3schools.com/php/php_ref_directory.asphttp://www.w3schools.com/php/php_ref_error.asphttp://www.w3schools.com/php/php_ref_filesystem.asphttp://www.w3schools.com/php/php_ref_filter.asphttp://www.w3schools.com/php/php_ref_ftp.asphttp://www.w3schools.com/php/php_ref_http.asphttp://www.w3schools.com/php/php_ref_libxml.asphttp://www.w3schools.com/php/php_ref_mail.asphttp://www.w3schools.com/php/php_ref_math.asphttp://www.w3schools.com/php/php_ref_misc.asphttp://www.w3schools.com/php/php_ref_mysql.asphttp://www.w3schools.com/php/php_ref_simplexml.asphttp://www.w3schools.com/php/php_ref_string.asphttp://www.w3schools.com/php/php_ref_xml.asphttp://www.w3schools.com/php/php_ref_zip.asp -
8/10/2019 Cara Pembuatan PHP Dasar
2/101
PHP )ntroduction Previous Next Chapter
PHP is a server-side scripting language.
What 5ou Should (lread 6now
7efore ou continue ou should ha!e a "asic understanding of thefollowing.
HTML/XHTML
ava!cript
)f ou want to stud these su"8ects first% find the tutorials on ourHome page#
What is PHP9 PHP stands "or PHP# H$pertext Preprocessor
PHP is a server-side scripting language% li&e '!P
PHP scripts are executed on the server PHP supports (an$ data)ases *M$!+L% ,n"or(ix% racle% !$)ase% !olid%
Postgre!+L% eneric 0C% etc.1 PHP is an open source so"t2are
PHP is "ree to do2nload and use
What is a PHP 1ile9 PHP "iles can contain text% HTML tags and scripts
PHP "iles are returned to the )ro2ser as plain HTML
PHP "iles have a "ile extension o" 3.php3% 3.php43% or 3.pht(l3
What is &S*29 M$!+L is a data)ase server
M$!+L is ideal "or )oth s(all and large applications
M$!+L supports standard !+L
M$!+L co(piles on a nu()er o" plat"or(s
http://www.w3schools.com/php/default.asphttp://www.w3schools.com/php/php_install.asphttp://www.w3schools.com/default.asphttp://www.w3schools.com/php/default.asphttp://www.w3schools.com/php/php_install.asphttp://www.w3schools.com/default.asp -
8/10/2019 Cara Pembuatan PHP Dasar
3/101
M$!+L is "ree to do2nload and use
PHP : &S*2 PHP co()ined 2ith M$!+L are cross-plat"or( *$ou can develop in 5indo2s and
serve on a 6nix plat"or(1
Wh PHP9 PHP runs on di""erent plat"or(s *5indo2s% Linux% 6nix% etc.1
PHP is co(pati)le 2ith al(ost all servers used toda$ *'pache% ,,!% etc.1
PHP is 7899 to do2nload "ro( the o""icial PHP resource#222.php.net
PHP is eas$ to learn and runs e""icientl$ on the server side
Where to Start9
To get access to a we" ser!er with PHP support% ou can.
,nstall 'pache *or ,,!1 on $our o2n server% install PHP% and M$!+L
r "ind a 2e) hosting plan 2ith PHP and M$!+L support
PHP )nstallation
Pre!ious Next Chapter
What do ou Need9
)f our ser!er supports PHP ou don't need to do anthing#
;ust create some #php files in our we" director% and the ser!er will parse them forou# 7ecause it is free% most we" hosts offer PHP support#
Howe!er% if our ser!er does not support PHP% ou must install PHP#
Here is a link to a good tutorial from PHP#net on how to install PHP
-
8/10/2019 Cara Pembuatan PHP Dasar
4/101
/ownload &S*2 for free here. http.==www#ms>l#com=downloads=
/ownload (pache Ser!er
/ownload (pache for free here. http.==httpd#apache#org=download#cgi
PHP Sntax
Pre!ious Next Chapter
PHP code is executed on the ser!er% and the plain HT&2 result is sentto the "rowser#
7asic PHP Sntax( PHP scripting "lock alwas starts with # ( PHP scripting"lock can "e placed anwhere in the document#
?n ser!ers with shorthand support ena"led ou can start a scripting "lock with @9and end with 9A#
1or maximum compati"ilit% we recommend that ou use the standard form B@9phprather than the shorthand form#
@9php9A
( PHP file normall contains HT&2 tags% 8ust like an HT&2 file% and some PHPscripting code#
7elow% we ha!e an example of a simple PHP script which sends the text DHello WorldDto the "rowser.
@htmlA@"odA
@9phpecho DHello WorldDE9A
@="odA@=htmlA
0ach code line in PHP must end with a semicolon# The semicolon is a separator and isused to distinguish one set of instructions from another#
http://www.mysql.com/downloads/http://httpd.apache.org/download.cgihttp://www.w3schools.com/php/php_install.asphttp://www.w3schools.com/php/php_variables.asphttp://www.mysql.com/downloads/http://httpd.apache.org/download.cgihttp://www.w3schools.com/php/php_install.asphttp://www.w3schools.com/php/php_variables.asp -
8/10/2019 Cara Pembuatan PHP Dasar
5/101
There are two "asic statements to output text with PHP. echoand print# )n theexample a"o!e we ha!e used the echo statement to output the text DHello WorldD#
Note:The file must ha!e a #php extension# )f the file has a #html extension% the PHPcode will not "e executed#
Comments in PHP
)n PHP% we use == to make a single$line comment or =F and F= to make a largecomment "lock#
@htmlA@"odA
@9php==This is a comment
=FThis isa comment"lockF=9A
@="odA@=htmlA
PHP Garia"les Previous Next Chapter
' varia)le is used to store in"or(ation.
Garia"les in PHP
Garia"les are used for storing !alues% like text strings% num"ers orarras#
When a !aria"le is declared% it can "e used o!er and o!er again in ourscript#
http://www.w3schools.com/php/php_syntax.asphttp://www.w3schools.com/php/php_string.asphttp://www.w3schools.com/php/php_syntax.asphttp://www.w3schools.com/php/php_string.asp -
8/10/2019 Cara Pembuatan PHP Dasar
6/101
(ll !aria"les in PHP start with a sign sm"ol#
The correct wa of declaring a !aria"le in PHP.
:var;na(e < value=
New PHP programmers often forget the sign at the "eginning of the!aria"le# )n that case it will not work#
2et's tr creating a !aria"le containing a string% and a !aria"lecontaining a num"er.
>?php:txt
-
8/10/2019 Cara Pembuatan PHP Dasar
7/101
PHP String Garia"les
Pre!ious Next Chapter
( string !aria"le is used to store and manipulate text#
String Garia"les in PHP
String !aria"les are used for !alues that contain characters#
)n this chapter we are going to look at the most common functions and operatorsused to manipulate strings in PHP#
(fter we create a string we can manipulate it# ( string can "e used directl in afunction or it can "e stored in a !aria"le#
7elow% the PHP script assigns the text DHello WorldD to a string !aria"le called txt.
@9phptxtIDHello WorldDEecho txtE9A
The output of the code a"o!e will "e.
Hello World
Now% lets tr to use some different functions and operators to manipulate the string#
The Concatenation ?perator
There is onl one string operator in PHP#
The concatenation operator B# is used to put two string !alues together#
To concatenate two string !aria"les together% use the concatenation operator.
@9phptxtJIDHello World,DEtxtKIDWhat a nice da,DEecho txtJ # D D # txtKE9A
The output of the code a"o!e will "e.
http://www.w3schools.com/php/php_variables.asphttp://www.w3schools.com/php/php_operators.asphttp://www.w3schools.com/php/php_variables.asphttp://www.w3schools.com/php/php_operators.asp -
8/10/2019 Cara Pembuatan PHP Dasar
8/101
Hello World, What a nice da,
)f we look at the code a"o!e ou see that we used the concatenation operator twotimes# This is "ecause we had to insert a third string Ba space character% to separatethe two strings#
The strlenB function
The strlenB function is used to return the length of a string#
2et's find the length of a string.
@9phpecho strlenBDHello world,DE9A
The output of the code a"o!e will "e.
JK
The length of a string is often used in loops or other functions% when it is importantto know when the string ends# Bi#e# in a loop% we would want to stop the loop afterthe last character in the string#
The strposB function
The strposB function is used to search for character within a string#
)f a match is found% this function will return the position of the first match# )f nomatch is found% it will return 1(2S0#
2et's see if we can find the string DworldD in our string.
@9phpecho strposBDHello world,D%DworldDE9A
The output of the code a"o!e will "e.
L
The position of the string DworldD in our string is position L# The reason that it is LBand not M% is that the first position in the string is % and not J#
-
8/10/2019 Cara Pembuatan PHP Dasar
9/101
Complete PHP String -eference
1or a complete reference of all string functions% go to our complete PHP String-eference#
The reference contains a "rief description% and examples of use% for each function,
PHP ?perators Previous Next Chapter
perators are used to operate on values.
PHP ?perators
This section lists the different operators used in PHP#
Arithmetic Operators
Operator Description Example Result
'ddition x
-
8/10/2019 Cara Pembuatan PHP Dasar
10/101
< x
-
8/10/2019 Cara Pembuatan PHP Dasar
11/101
Conditional state(ents are used to per"or( di""erent actions )ased on di""erentconditions.
Conditional StatementsGer often when ou write code% ou want to perform different actionsfor different decisions#
5ou can use conditional statements in our code to do this#
)n PHP we ha!e the following conditional statements.
if statement- use this state(ent to execute so(e code onl$ i" a speci"iedcondition is true
if...else statement- use this state(ent to execute so(e code i" a condition is trueand another code i" the condition is "alse
if...elseif....else statement- use this state(ent to select one o" several )loc&s o"code to )e executed
switch statement- use this state(ent to select one o" (an$ )loc&s o" code to )e
executed
The if Statement
Qse the if statement to execute some code onl if a specified conditionis true#
Syntax
i" *condition1 code to be executed if condition is true;
The following example will output DHa!e a nice weekend,D if thecurrent da is 1rida.
>ht(l
>)od$
>?php:d
-
8/10/2019 Cara Pembuatan PHP Dasar
12/101
>/ht(l
Notice that there is no ##else## in this sntax# The code is executedonly if the specifie conition is tre#
The if###else Statement
Qse the if####else statement to execute some code if a condition is trueand another code if a condition is false#
Syntax
i" *condition1 code to be executed if condition is true;else code to be executed if condition is false;
Example
The following example will output DHa!e a nice weekend,D if thecurrent da is 1rida% otherwise it will output DHa!e a nice da,D.
>ht(l>)od$
>?php:dht(l>)od$
>?php:d
-
8/10/2019 Cara Pembuatan PHP Dasar
13/101
-
8/10/2019 Cara Pembuatan PHP Dasar
14/101
>/ht(l
PHP Switch Statement Previous Next Chapter
Conditional state(ents are used to per"or( di""erent actions )ased on di""erentconditions.
The PHP Switch Statement
Qse the switch statement to select one of man "locks of code to "eexecuted#
Syntax
s2itch *n1Rcase label1: code to be executed if n=label1; )rea&=case label2: code to be executed if n=label2; )rea&=de"ault# code to be executed if n is different from both label1 and label2;S
This is how it works. 1irst we ha!e a single expression nBmost often a!aria"le% that is e!aluated once# The !alue of the expression is thencompared with the !alues for each case in the structure# )f there is amatch% the "lock of code associated with that case is executed# Qse"rea#to pre!ent the code from running into the next case
automaticall# The default statement is used if no match is found#Example
>ht(l>)od$
>?phps2itch *:x1
http://www.w3schools.com/php/php_if_else.asphttp://www.w3schools.com/php/php_arrays.asphttp://www.w3schools.com/php/php_if_else.asphttp://www.w3schools.com/php/php_arrays.asp -
8/10/2019 Cara Pembuatan PHP Dasar
15/101
Rcase A# echo 3Nu()er A3= )rea&=case I#
echo 3Nu()er I3= )rea&=case 4# echo 3Nu()er 43= )rea&=de"ault# echo 3No nu()er )et2een A and 43=S?
>/)od$
>/ht(l
PHP (rras Previous Next Chapter
'n arra$ stores (ultiple values in one single varia)le.
What is an (rra9( !aria"le is a storage area holding a num"er or text# The pro"lem is%a !aria"le will hold onl one !alue#
(n arra is a special !aria"le% which can store multiple !alues in onesingle !aria"le#
)f ou ha!e a list of items Ba list of car names% for example% storingthe cars in single !aria"les could look like this.
:carsA
-
8/10/2019 Cara Pembuatan PHP Dasar
16/101
The "est solution here is to use an arra,
(n arra can hold all our !aria"le !alues under a single name# (ndou can access the !alues " referring to the arra name#
0ach element in the arra has its own index so that it can "e easilaccessed#
)n PHP% there are three kind of arras.
Numeric array- 'n arra$ 2ith a nu(eric index
Associatie array- 'n arra$ 2here each , &e$ is associated 2ith a value
!ulti"imensional array- 'n arra$ containing one or (ore arra$s
Numeric (rras( numeric arra stores each arra element with a numeric index#
There are two methods to create a numeric arra#
J# )n the following example the index are automaticall assigned Btheindex starts at .
:cars
-
8/10/2019 Cara Pembuatan PHP Dasar
17/101
?
The code a"o!e will output.
!aa) and olvo are !2edish cars.
(ssociati!e (rras
(n associati!e arra% each )/ ke is associated with a !alue#
When storing data a"out specific named !alues% a numerical arra isnot alwas the "est wa to do it#
With associati!e arras we can use the !alues as kes and assign
!alues to them#
Example 1
)n this example we use an arra to assign ages to the differentpersons.
:ages < arra$*3Peter3?php
:agesUWPeterWV < 34I3=:agesUW+uag(ireWV < 34F3=:agesUWoeWV < 34J3=
echo 3Peter is 3 . :agesUWPeterWV . 3 $ears old.3=?
The code a"o!e will output.
-
8/10/2019 Cara Pembuatan PHP Dasar
18/101
Peter is 4I $ears old.
&ultidimensional (rras
)n a multidimensional arra% each element in the main arra can also"e an arra# (nd each element in the su"$arra can "e an arra% andso on#
Example
)n this example we create a multidimensional arra% with automaticallassigned )/ kes.
:"a(ilies < arra$
* 3ri""in3
-
8/10/2019 Cara Pembuatan PHP Dasar
19/101
* UFV
-
8/10/2019 Cara Pembuatan PHP Dasar
20/101
foreach - loops through a )loc& o" code "or each ele(ent in an arra$
The while 2oop
The while loop executes a "lock of code while a condition is true#
Syntax
2hile *condition1 R code to be executed= S
Example
The example "elow defines a loop that starts with iIJ# The loop willcontinue to run as long as i is less than% or e>ual to
-
8/10/2019 Cara Pembuatan PHP Dasar
21/101
The do###while Statement
The do###while statement will alwas execute the "lock of code once% itwill then check the condition% and repeat the loop while the condition is
true#Syntax
do R code to be executed; S2hile *condition1=
Example
The example "elow defines a loop that starts with iIJ# )t will thenincrement i with J% and write some output# Then the condition ischecked% and the loop will continue to run as long as i is less than% ore>ual to ht(l>)od$
>?php:i)r /3= S2hile *:i>/)od$>/ht(l
?utput.
The nu()er is IThe nu()er is 4The nu()er is JThe nu()er is KThe nu()er is B
The for loop and the foreach loop will "e explained in the next chapter#
-
8/10/2019 Cara Pembuatan PHP Dasar
22/101
PHP 2ooping $ 1or 2oops Previous Next Chapter
Loops execute a )loc& o" code a speci"ied nu()er o" ti(es% or 2hile a speci"ied conditionis true.
The for 2oop
The for loop is used when ou know in ad!ance how man times thescript should run#
Syntax"or *init; condition; increment1 R code to be executed; S
Parameters.
init# Mostl$ used to set a counter *)ut can )e an$ code to )e executed once at the
)eginning o" the loop1 condition# 9valuated "or each loop iteration. ," it evaluates to T869% the loop
continues. ," it evaluates to 7'L!9% the loop ends. increment# Mostl$ used to incre(ent a counter *)ut can )e an$ code to )e
executed at the end o" the loop1
Note: 0ach of the parameters a"o!e can "e empt% or ha!e multipleexpressions Bseparated " commas#
Example
The example "elow defines a loop that starts with iIJ# The loop will
continue to run as long as i is less than% or e>ual to
-
8/10/2019 Cara Pembuatan PHP Dasar
23/101
R echo 3The nu()er is 3 . :i . 3>)r /3= S?
>/)od$>/ht(l
?utput.
The nu()er is AThe nu()er is IThe nu()er is 4The nu()er is JThe nu()er is K
The foreach 2oop
The foreach loop is used to loop through arras#
Syntax
"oreach *:array as:value1 R code to be executed; S
1or e!er loop iteration% the !alue of the current arra element isassigned to !alue Band the arra pointer is mo!ed " one $ so on thenext loop iteration% ou'll "e looking at the next arra !alue#
Example
The following example demonstrates a loop that will print the !alues ofthe gi!en arra.
>ht(l>)od$
>?php:x
-
8/10/2019 Cara Pembuatan PHP Dasar
24/101
S?
>/)od$>/ht(l
?utput.
onet2othree
PHP 1unctions
Previous Next Chapter
The real po2er o" PHP co(es "ro( its "unctions.
,n PHP% there are (ore than FF )uilt-in "unctions.
PHP 7uilt$in 1unctions
1or a complete reference and examples of the "uilt$in functions% please!isit our PHP -eference#
PHP 1unctions
)n this chapter we will show ou how to create our own functions#
To keep the script from "eing executed when the page loads% ou can
put it into a function#( function will "e executed " a call to the function#
5ou ma call a function from anwhere within a page#
http://www.w3schools.com/php/php_looping_for.asphttp://www.w3schools.com/php/php_forms.asphttp://www.w3schools.com/php/default.asphttp://www.w3schools.com/php/php_looping_for.asphttp://www.w3schools.com/php/php_forms.asphttp://www.w3schools.com/php/default.asp -
8/10/2019 Cara Pembuatan PHP Dasar
25/101
Create a PHP 1unction
( function will "e executed " a call to the function#
Syntax
"unctionfunctionName*1Rcode to be executed=S
PHP function guidelines.
ive the "unction a na(e that re"lects 2hat the "unction does
The "unction na(e can start 2ith a letter or underscore *not a nu()er1
Example
( simple function that writes m name when it is called.
>ht(l>)od$
>?php"unction 2riteNa(e*1Recho 3Yai i( 8e"snes3=
S
echo 3M$ na(e is 3=2riteNa(e*1=?
>/)od$>/ht(l
?utput.
M$ na(e is Yai i( 8e"snes
PHP 1unctions $ (dding parameters
To add more functionalit to a function% we can add parameters# (parameter is 8ust like a !aria"le#
-
8/10/2019 Cara Pembuatan PHP Dasar
26/101
Parameters are specified after the function name% inside theparentheses#
Example 1
The following example will write different first names% "ut e>ual lastname.
>ht(l>)od$
>?php"unction 2riteNa(e*:"na(e1Recho :"na(e . 3 8e"snes.>)r /3=S
echo 3M$ na(e is 3=2riteNa(e*3Yai i(31=echo 3M$ sisterWs na(e is 3=2riteNa(e*3Hege31=echo 3M$ )rotherWs na(e is 3=2riteNa(e*3!tale31=?
>/)od$>/ht(l
?utput.
M$ na(e is Yai i( 8e"snes.M$ sisterWs na(e is Hege 8e"snes.M$ )rotherWs na(e is !tale 8e"snes.
Example 2
The following function has two parameters.
>ht(l>)od$
>?php"unction 2riteNa(e*:"na(e%:punctuation1Recho :"na(e . 3 8e"snes3 . :punctuation . 3>)r /3=S
-
8/10/2019 Cara Pembuatan PHP Dasar
27/101
echo 3M$ na(e is 3=2riteNa(e*3Yai i(3%3.31=echo 3M$ sisterWs na(e is 3=2riteNa(e*3Hege3%3@31=
echo 3M$ )rotherWs na(e is 3=2riteNa(e*3!tZle3%3?31=?
>/)od$>/ht(l
?utput.
M$ na(e is Yai i( 8e"snes.M$ sisterWs na(e is Hege 8e"snes@
M$ )rotherWs na(e is !tZle 8e"snes?
PHP 1unctions $ -eturn !alues
To let a function return a !alue% use the return statement#
Example
>ht(l>)od$
>?php"unction add*:x%:$1R:total/)od$>/ht(l
?utput.
A AB < A
-
8/10/2019 Cara Pembuatan PHP Dasar
28/101
PHP 1orms and Qser )nput
Pre!ious Next Chapter
The PHP :;9T and :;P!T varia)les are used to retrieve in"or(ation "ro( "or(s% li&euser input.
PHP 1orm Handling
The most important thing to notice when dealing with HT&2 forms and PHP is thatan form element in an HT&2 page will atomatically"e a!aila"le to our PHPscripts#
Example
The example "elow contains an HT&2 form with two input fields and a su"mit"utton.
@htmlA@"odA
@form actionIDwelcome#phpD methodIDpostDAName. @input tpeIDtextD nameIDfnameD =A(ge. @input tpeIDtextD nameIDageD =A@input tpeIDsu"mitD =A
@=formA
@="odA@=htmlA
When a user fills out the form a"o!e and click on the su"mit "utton% the form data issent to a PHP file% called Dwelcome#phpD.
Dwelcome#phpD looks like this.
@htmlA@"odA
Welcome @9php echo RP?STDfnameDE 9A,@"r =A5ou are @9php echo RP?STDageDE 9A ears old#
@="odA@=htmlA
?utput could "e something like this.
http://www.w3schools.com/php/php_functions.asphttp://www.w3schools.com/php/php_get.asphttp://www.w3schools.com/php/php_functions.asphttp://www.w3schools.com/php/php_get.asp -
8/10/2019 Cara Pembuatan PHP Dasar
29/101
Welcome ;ohn,5ou are KU ears old#
The PHP RV0T and RP?ST functions will "e explained in the next chapters#
1orm Galidation
Qser input should "e !alidated on the "rowser whene!er possi"le B" client scripts#7rowser !alidation is faster and reduces the ser!er load#
5ou should consider ser!er !alidation if the user input will "e inserted into adata"ase# ( good wa to !alidate a form on the ser!er is to post the form to itself%instead of 8umping to a different page# The user will then get the error messages onthe same page as the form# This makes it easier to disco!er the error#
PHP RV0T 1unction Previous Next Chapter
The )uilt-in :;9T "unction is used to collect values in a "or( 2ith (ethodinput t$pe
-
8/10/2019 Cara Pembuatan PHP Dasar
30/101
http#//222.24schools.co(/2elco(e.php?"na(e)r /[ou are >?php echo :;9TU3age3V= ? $ears old@
When to use methodIDgetD9
When using methodIDgetD in HT&2 forms% all !aria"le names and!alues are displaed in the Q-2#
Note:This method should not "e used when sending passwords orother sensiti!e information,
Howe!er% "ecause the !aria"les are displaed in the Q-2% it is possi"leto "ookmark the page# This can "e useful in some cases#
Note:The get method is not suita"le for !er large !aria"le !alues# )tshould not "e used with !alues exceeding K characters#
PHP RP?ST 1unction Previous Next Chapter
The )uilt-in :;P!T "unction is used to collect values in a "or( 2ith (ethod
-
8/10/2019 Cara Pembuatan PHP Dasar
31/101
Note:Howe!er% there is an U &" max si+e for the P?ST method% "default Bcan "e changed " setting the postRmaxRsi+e in the php#inifile#
Example
>"or( action)r /[ou are >?php echo :;P!TU3age3V= ? $ears old.
When to use methodIDpostD9
)nformation sent from a form with the P?ST method is in!isi"le toothers and has no limits on the amount of information to send#
Howe!er% "ecause the !aria"les are not displaed in the Q-2% it is notpossi"le to "ookmark the page#
The PHP R-0*Q0ST 1unction
The PHP "uilt$in R-0*Q0ST function contains the contents of "oth
RV0T% RP?ST% and RC??6)0#
The R-0*Q0ST function can "e used to collect form data sent with"oth the V0T and P?ST methods#
Example
5elco(e >?php echo :;89+69!TU3"na(e3V= ?@>)r /
-
8/10/2019 Cara Pembuatan PHP Dasar
32/101
[ou are >?php echo :;89+69!TU3age3V= ? $ears old.
PHP /ateB1unction
Pre!ious Next Chapter
The PHP date*1 "unction is used to "or(at a ti(e and/or date.
The PHP /ateB 1unction
The PHP dateB function formats a timestamp to a more reada"le date and time#
( timestamp is a se>uence of characters% denoting the date and=or time at which acertain e!ent occurred#
Syntax
dateBformat%timestamp
Parameter $escription
format -e>uired# Specifies the format of the timestamp
timestamp ?ptional# Specifies a timestamp# /efault is the current date and time
PHP /ateB $ 1ormat the /ate
The re>uired formatparameter in the dateB function specifies how to format thedate=time#
Here are some characters that can "e used.
d $ -epresents the da of the month BJ to 3J m $ -epresents a month BJ to JK 5 $ -epresents a ear Bin four digits
( list of all the characters that can "e used in the formatparameter% can "e found inour PHP /ate reference#
?ther characters% likeD=D% D#D% or D$D can also "e inserted "etween the letters to addadditional formatting.
@9php
http://www.w3schools.com/php/php_post.asphttp://www.w3schools.com/php/php_includes.asphttp://www.w3schools.com/php/php_ref_date.asphttp://www.w3schools.com/php/php_post.asphttp://www.w3schools.com/php/php_includes.asphttp://www.w3schools.com/php/php_ref_date.asp -
8/10/2019 Cara Pembuatan PHP Dasar
33/101
echo dateBD5=m=dD # D@"r =ADEecho dateBD5#m#dD # D@"r =ADEecho dateBD5$m$dD9A
The output of the code a"o!e could "e something like this.
K=
-
8/10/2019 Cara Pembuatan PHP Dasar
34/101
Pre!ious Next Chapter
Ser!er Side )ncludes BSS)
5ou can insert the content of one PHP file into another PHP file "efore the ser!erexecutes it% with the includeB or re>uireB function#
The two functions are identical in e!er wa% except how the handle errors.
includeB generates a warning% "ut the script will continue execution re>uireB generates a fatal error% and the script will stop
These two functions are used to create functions% headers% footers% or elements thatwill "e reused on multiple pages#
Ser!er side includes sa!es a lot of work# This means that ou can create a standard
header% footer% or menu file for all our we" pages# When the header needs to "eupdated% ou can onl update the include file% or when ou add a new page to oursite% ou can simpl change the menu file Binstead of updating the links on all ourwe" pages#
PHP includeB 1unction
The includeB function takes all the content in a specified file and includes it in thecurrent file#
)f an error occurs% the includeB function generates a warning% "ut the script willcontinue execution#
Example 1
(ssume that ou ha!e a standard header file% called Dheader#phpD# To include theheader file in a page% use the includeB function.
@htmlA@"odA
@9php includeBDheader#phpDE 9A
@hJAWelcome to m home page,@=hJA@pASome text#@=pA
@="odA@=htmlA
http://www.w3schools.com/php/php_date.asphttp://www.w3schools.com/php/php_file.asphttp://www.w3schools.com/php/php_date.asphttp://www.w3schools.com/php/php_file.asp -
8/10/2019 Cara Pembuatan PHP Dasar
35/101
Example 2
(ssume we ha!e a standard menu file% called Dmenu#phpD% that should "e used on allpages.
@a hrefID=default#phpDAHome@=aA@a hrefID=tutorials#phpDATutorials@=aA@a hrefID=references#phpDA-eferences@=aA@a hrefID=examples#phpDA0xamples@=aA@a hrefID=a"out#phpDA("out Qs@=aA@a hrefID=contact#phpDAContact Qs@=aA
(ll pages in the We" site should include this menu file# Here is how it can "e done.
@htmlA@"odA
@di! classIDleftmenuDA
@9php includeBDmenu#phpDE 9A@=di!A
@hJAWelcome to m home page#@=hJA@pASome text#@=pA
@="odA@=htmlA
)f ou look at the source code of the page a"o!e Bin a "rowser% it will look like this.
@htmlA
@"odA
@di! classIDleftmenuDA@a hrefID=default#phpDAHome@=aA@a hrefID=tutorials#phpDATutorials@=aA@a hrefID=references#phpDA-eferences@=aA@a hrefID=examples#phpDA0xamples@=aA@a hrefID=a"out#phpDA("out Qs@=aA@a hrefID=contact#phpDAContact Qs@=aA@=di!A
@hJAWelcome to m home page,@=hJA@pASome text#@=pA
@="odA@=htmlA
PHP re>uireB 1unction
-
8/10/2019 Cara Pembuatan PHP Dasar
36/101
The re>uireB function is identical to includeB% except that it handles errorsdifferentl#
)f an error occurs% the includeB function generates a warning% "ut the script willcontinue execution# The re>uireB generates a fatal error% and the script will stop#
Error Example include() Function
@htmlA@"odA
@9phpincludeBDwrong1ile#phpDEecho DHello World,DE9A
@="odA@=htmlA
0rror message.
%arning:includeBwrong1ile#php function#include.failed to open stream.No such file or director in C.XhomeXwe"siteXtest#php on line ?php:"ile < "open*32elco(e.txt3% 3r31 or exit*36na)le to open "ile@31=//utput a line o" the "ile until the end is reached2hile*@"eo"*:"ile11 R echo "gets*:"ile1. 3>)r /3= S"close*:"ile1=
?
-eading a 1ile Character " Character
The fgetcB function is used to read a single character from a file#
-
8/10/2019 Cara Pembuatan PHP Dasar
40/101
-
8/10/2019 Cara Pembuatan PHP Dasar
41/101
>/ht(l
Notice the following a"out the HT&2 form a"o!e.
The enct$pe attri)ute o" the >"or( tag speci"ies 2hich content-t$pe to use 2hen
su)(itting the "or(. 3(ultipart/"or(-data3 is used 2hen a "or( reOuires )inar$data% li&e the contents o" a "ile% to )e uploaded
The t$peinput tag speci"ies that the input should )e
processed as a "ile. 7or exa(ple% 2hen vie2ed in a )ro2ser% there 2ill )e a)ro2se-)utton next to the input "ield
Note:(llowing users to upload files is a "ig securit risk# ?nl permittrusted users to perform file uploads#
Create The Qpload ScriptThe DuploadRfile#phpD file contains the code for uploading a file.
>?phpi" *:;7,L9!U3"ile3VU3error3V F1 R echo 39rror# 3 . :;7,L9!U3"ile3VU3error3V . 3>)r /3= Selse R
echo 36pload# 3 . :;7,L9!U3"ile3VU3na(e3V . 3>)r /3= echo 3T$pe# 3 . :;7,L9!U3"ile3VU3t$pe3V . 3>)r /3= echo 3!iDe# 3 . *:;7,L9!U3"ile3VU3siDe3V / AFIJ1 . 3 Y)>)r /3= echo 3!tored in# 3 . :;7,L9!U3"ile3VU3t(p;na(e3V= S?
7 using the glo"al PHP R1)20S arra ou can upload files from aclient computer to the remote ser!er#
The first parameter is the form's input name and the second index can"e either DnameD% DtpeD% Dsi+eD% DtmpRnameD or DerrorD# 2ike this.
:;7,L9!U3"ile3VU3na(e3V - the na(e o" the uploaded "ile
:;7,L9!U3"ile3VU3t$pe3V - the t$pe o" the uploaded "ile
:;7,L9!U3"ile3VU3siDe3V - the siDe in )$tes o" the uploaded "ile
:;7,L9!U3"ile3VU3t(p;na(e3V - the na(e o" the te(porar$ cop$ o" the "ile stored
on the server
-
8/10/2019 Cara Pembuatan PHP Dasar
42/101
:;7,L9!U3"ile3VU3error3V - the error code resulting "ro( the "ile upload
This is a !er simple wa of uploading files# 1or securit reasons% oushould add restrictions on what the user is allowed to upload#
-estrictions on Qpload
)n this script we add some restrictions to the file upload# The user maonl upload #gif or #8peg files and the file si+e must "e under K k".
>?phpi" ***:;7,L9!U3"ile3VU3t$pe3V IFFFF11 R i" *:;7,L9!U3"ile3VU3error3V F1 R echo 39rror# 3 . :;7,L9!U3"ile3VU3error3V . 3>)r /3= S else R echo 36pload# 3 . :;7,L9!U3"ile3VU3na(e3V . 3>)r /3= echo 3T$pe# 3 . :;7,L9!U3"ile3VU3t$pe3V . 3>)r /3= echo 3!iDe# 3 . *:;7,L9!U3"ile3VU3siDe3V / AFIJ1 . 3 Y)>)r /3=
echo 3!tored in# 3 . :;7,L9!U3"ile3VU3t(p;na(e3V= S Selse R echo 3,nvalid "ile3= S?
Note:1or )0 to recogni+e 8pg files the tpe must "e p8peg% for 1ire1oxit must "e 8peg#
Sa!ing the Qploaded 1ile
The examples a"o!e create a temporar cop of the uploaded files inthe PHP temp folder on the ser!er#
-
8/10/2019 Cara Pembuatan PHP Dasar
43/101
The temporar copied files disappears when the script ends# To storethe uploaded file we need to cop it to a different location.
>?phpi" ***:;7,L9!U3"ile3VU3t$pe3V )r /3=
echo 3T$pe# 3 . :;7,L9!U3"ile3VU3t$pe3V . 3>)r /3= echo 3!iDe# 3 . *:;7,L9!U3"ile3VU3siDe3V / AFIJ1 . 3 Y)>)r /3= echo 3Te(p "ile# 3 . :;7,L9!U3"ile3VU3t(p;na(e3V . 3>)r /3=
i" *"ile;exists*3upload/3 . :;7,L9!U3"ile3VU3na(e3V11 R echo :;7,L9!U3"ile3VU3na(e3V . 3 alread$ exists. 3= S else R (ove;uploaded;"ile*:;7,L9!U3"ile3VU3t(p;na(e3V%
3upload/3 . :;7,L9!U3"ile3VU3na(e3V1= echo 3!tored in# 3 . 3upload/3 . :;7,L9!U3"ile3VU3na(e3V= S S Selse R echo 3,nvalid "ile3= S?
The script a"o!e checks if the file alread exists% if it does not% itcopies the file to the specified folder#
Note:This example sa!es the file to a new folder called DuploadD
PHP Cookies
-
8/10/2019 Cara Pembuatan PHP Dasar
44/101
Previous Next Chapter
' coo&ie is o"ten used to identi"$ a user.
What is a Cookie9
( cookie is often used to identif a user# ( cookie is a small file thatthe ser!er em"eds on the user's computer# 0ach time the samecomputer re>uests a page with a "rowser% it will send the cookie too#With PHP% ou can "oth create and retrie!e cookie !alues#
How to Create a Cookie9The setcookieB function is used to set a cookie#
Note:The setcookieB function must appear 701?-0 the @htmlA tag#
Syntax
setcoo&ie*na(e% value% expire% path% do(ain1=
Example 1
)n the example "elow% we will create a cookie named DuserD and assignthe !alue D(lex PorterD to it# We also specif that the cookie shouldexpire after one hour.
>?phpsetcoo&ie*3user3% 3'lex Porter3% ti(e*14BFF1=?
>ht(l.....
Note: The !alue of the cookie is automaticall Q-2encoded whensending the cookie% and automaticall decoded when recei!ed Btopre!ent Q-2encoding% use setrawcookieB instead#
http://www.w3schools.com/php/php_file_upload.asphttp://www.w3schools.com/php/php_sessions.asphttp://www.w3schools.com/php/php_file_upload.asphttp://www.w3schools.com/php/php_sessions.asp -
8/10/2019 Cara Pembuatan PHP Dasar
45/101
Example 2
5ou can also set the expiration time of the cookie in another wa# )tma "e easier than using seconds#
>?php:expire)r /3=else echo 35elco(e guest@>)r /3=?
-
8/10/2019 Cara Pembuatan PHP Dasar
46/101
>/)od$>/ht(l
How to /elete a Cookie9When deleting a cookie ou should assure that the expiration date is inthe past#
/elete example.
>?php// set the expiration date to one hour agosetcoo&ie*3user3% 33% ti(e*1-4BFF1=
?
What if a 7rowser /oes N?T SupportCookies9
)f our application deals with "rowsers that do not support cookies%ou will ha!e to use other methods to pass information from one pageto another in our application# ?ne method is to pass the data through
forms Bforms and user input are descri"ed earlier in this tutorial#
The form "elow passes the user input to Dwelcome#phpD when the userclicks on the DSu"mitD "utton.
>ht(l>)od$
>"or( action
-
8/10/2019 Cara Pembuatan PHP Dasar
47/101
>ht(l>)od$
5elco(e >?php echo :;P!TU3na(e3V= ?.>)r /[ou are >?php echo :;P!TU3age3V= ? $ears old.
>/)od$>/ht(l
PHP Sessions Previous Next Chapter
' PHP session varia)le is used to store in"or(ation a)out% or change settings "or a usersession. !ession varia)les hold in"or(ation a)out one single user% and are availa)le to allpages in one application.
PHP Session Garia"les
When ou are working with an application% ou open it% do somechanges and then ou close it# This is much like a Session# Thecomputer knows who ou are# )t knows when ou start the application
and when ou end# 7ut on the internet there is one pro"lem. the we"ser!er does not know who ou are and what ou do "ecause the HTTPaddress doesn't maintain state#
( PHP session sol!es this pro"lem " allowing ou to store userinformation on the ser!er for later use Bi#e# username% shopping items%etc# Howe!er% session information is temporar and will "e deletedafter the user has left the we"site# )f ou need a permanent storageou ma want to store the data in a data"ase#
Sessions work " creating a uni>ue id BQ)/ for each !isitor and store!aria"les "ased on this Q)/# The Q)/ is either stored in a cookie or ispropagated in the Q-2#
Starting a PHP Session
http://www.w3schools.com/php/php_cookies.asphttp://www.w3schools.com/php/php_mail.asphttp://www.w3schools.com/php/php_cookies.asphttp://www.w3schools.com/php/php_mail.asp -
8/10/2019 Cara Pembuatan PHP Dasar
48/101
7efore ou can store user information in our PHP session% ou mustfirst start up the session#
Note:The sessionRstartB function must appear 701?-0 the @htmlAtag.
>?php session;start*1= ?
>ht(l>)od$
>/)od$>/ht(l
The code a"o!e will register the user's session with the ser!er% allowou to start sa!ing user information% and assign a Q)/ for that user's
session#
Storing a Session Garia"le
The correct wa to store and retrie!e session !aria"les is to use thePHP RS0SS)?N !aria"le.
>?phpsession;start*1=// store session data:;!9!!,NUWvie2sWVht(l>)od$
>?php//retrieve session dataecho 3Pagevie2s/)od$>/ht(l
?utput.
Pagevie2s
-
8/10/2019 Cara Pembuatan PHP Dasar
49/101
)n the example "elow% we create a simple page$!iews counter# TheissetB function checks if the D!iewsD !aria"le has alread "een set# )fD!iewsD has "een set% we can increment our counter# )f D!iewsD doesn'texist% we create a D!iewsD !aria"le% and set it to J.
>?phpsession;start*1=
i"*isset*:;!9!!,NUWvie2sWV11:;!9!!,NUWvie2sWV?phpsession;destro$*1=?
Note:sessionRdestroB will reset our session and ou will lose allour stored session data#
PHP Sending 0$mails Previous Next Chapter
http://www.w3schools.com/php/php_sessions.asphttp://www.w3schools.com/php/php_secure_mail.asphttp://www.w3schools.com/php/php_sessions.asphttp://www.w3schools.com/php/php_secure_mail.asp -
8/10/2019 Cara Pembuatan PHP Dasar
50/101
PHP allo2s $ou to send e-(ails directl$ "ro( a script.
The PHP mailB 1unction
The PHP mailB function is used to send emails from inside a script#
Synta'
(ail*to%su)\ect%(essage%headers%para(eters1
Parameter Description
to 8eOuired. !peci"ies the receiver / receivers o" the e(ail
su)\ect 8eOuired. !peci"ies the su)\ect o" the e(ail. Note#This para(eter
cannot contain an$ ne2line characters(essage 8eOuired. e"ines the (essage to )e sent. 9ach line should )e separated
2ith a L7 *]n1. Lines should not exceed F characters
headers ptional. !peci"ies additional headers% li&e 7ro(% Cc% and 0cc. Theadditional headers should )e separated 2ith a C8L7 *]r]n1
para(eters ptional. !peci"ies an additional para(eter to the send(ail progra(
Note:1or the mail functions to "e a!aila"le% PHP re>uires an installedand working email sstem# The program to "e used is defined " theconfiguration settings in the php#ini file# -ead more in our PHP &ail
reference#
PHP Simple 0$&ail
The simplest wa to send an email with PHP is to send a text email#
)n the example "elow we first declare the !aria"les Bto% su"8ect%message% from% headers% then we use the !aria"les in the mailBfunction to send an e$mail.
>?php:to < 3so(eone^exa(ple.co(3=:su)\ect < 3Test (ail3=:(essage < 3Hello@ This is a si(ple e(ail (essage.3=:"ro( < 3so(eonelse^exa(ple.co(3=:headers < 37ro(# :"ro(3=(ail*:to%:su)\ect%:(essage%:headers1=
http://www.w3schools.com/php/php_ref_mail.asphttp://www.w3schools.com/php/php_ref_mail.asphttp://www.w3schools.com/php/php_ref_mail.asphttp://www.w3schools.com/php/php_ref_mail.asp -
8/10/2019 Cara Pembuatan PHP Dasar
51/101
echo 3Mail !ent.3=?
PHP &ail 1ormWith PHP% ou can create a feed"ack$form on our we"site# Theexample "elow sends a text message to a specified e$mail address.
>ht(l>)od$
>?phpi" *isset*:;89+69!TUWe(ailWV11//i" 3e(ail3 is "illed out% send e(ail
R //send e(ail :e(ail < :;89+69!TUWe(ailWV = :su)\ect < :;89+69!TUWsu)\ectWV = :(essage < :;89+69!TUW(essageWV = (ail* 3so(eone^exa(ple.co(3% 3!u)\ect# :su)\ect3% :(essage% 37ro(# :e(ail3 1= echo 3Than& $ou "or using our (ail "or(3= Selse//i" 3e(ail3 is not "illed out% displa$ the "or(
R echo 3>"or( (ethod/)od$>/ht(l
This is ho2 the exa(ple a)ove 2or&s# 7irst% chec& i" the e(ail input "ield is "illed out
," it is not set *li&e 2hen the page is "irst visited1= output the HTML "or(
," it is set *a"ter the "or( is "illed out1= send the e(ail "ro( the "or(
-
8/10/2019 Cara Pembuatan PHP Dasar
52/101
5hen su)(it is pressed a"ter the "or( is "illed out% the page reloads% sees that the
e(ail input is set% and sends the e(ail
Note:This is the simplest wa to send e$mail% "ut it is not secure# )nthe next chapter of this tutorial ou can read more a"out
!ulnera"ilities in e$mail scripts% and how to !alidate user input to makeit more secure#
PHP Secure 0$mails Previous Next Chapter
There is a 2ea&ness in the PHP e-(ail script in the previous chapter.
PHP 0$mail )n8ections
1irst% look at the PHP code from the pre!ious chapter.
>ht(l>)od$
>?phpi" *isset*:;89+69!TUWe(ailWV11//i" 3e(ail3 is "illed out% send e(ail R //send e(ail :e(ail < :;89+69!TUWe(ailWV = :su)\ect < :;89+69!TUWsu)\ectWV = :(essage < :;89+69!TUW(essageWV = (ail*3so(eone^exa(ple.co(3% 3!u)\ect# :su)\ect3% :(essage% 37ro(# :e(ail3 1= echo 3Than& $ou "or using our (ail "or(3= Selse
//i" 3e(ail3 is not "illed out% displa$ the "or( R echo 3>"or( (ethod
-
8/10/2019 Cara Pembuatan PHP Dasar
53/101
>input t$pe/"or(3= S?
>/)od$>/ht(l
The pro"lem with the code a"o!e is that unauthori+ed users can insertdata into the mail headers !ia the input form#
What happens if the user adds the following text to the email inputfield in the form9
so(eone^exa(ple.co(F'Cc#personI^exa(ple.co(F'0cc#person4^exa(ple.co(%person4^exa(ple.co(%
anotherpersonJ^exa(ple.co(%personK^exa(ple.co(F'0To#personB^exa(ple.co(
The mailB function puts the text a"o!e into the mail headers as usual%and now the header has an extra Cc.% 7cc.% and To. field# When theuser clicks the su"mit "utton% the e$mail will "e sent to all of theaddresses a"o!e,
PHP Stopping 0$mail )n8ections
The "est wa to stop e$mail in8ections is to !alidate the input#
The code "elow is the same as in the pre!ious chapter% "ut now weha!e added an input !alidator that checks the email field in the form.
>ht(l>)od$>?php"unction spa(chec&*:"ield1 R //"ilter;var*1 sanitiDes the e-(ail //address using 7,LT98;!'N,T,E9;9M',L :"ield
-
8/10/2019 Cara Pembuatan PHP Dasar
54/101
R return T869= S else R
return 7'L!9= S S
i" *isset*:;89+69!TUWe(ailWV11 R//i" 3e(ail3 is "illed out% proceed
//chec& i" the e(ail address is invalid :(ailchec& < spa(chec&*:;89+69!TUWe(ailWV1= i" *:(ailchec&
-
8/10/2019 Cara Pembuatan PHP Dasar
55/101
The 7,LT98;!'N,T,E9;9M',L "ilter re(oves all illegal e-(ail characters "ro(
a string The 7,LT98;'L,'T9;9M',L "ilter validates value as an e-(ail address
5ou can read more a"out filters in our PHP 1ilterchapter#
PHP 0rror Handling Previous Next Chapter
The de"ault error handling in PHP is ver$ si(ple. 'n error (essage 2ith "ilena(e% linenu()er and a (essage descri)ing the error is sent to the )ro2ser.
PHP 0rror Handling
When creating scripts and we" applications% error handling is animportant part# )f our code lacks error checking code% our programma look !er unprofessional and ou ma "e open to securit risks#
This tutorial contains some of the most common error checkingmethods in PHP#
We will show different error handling methods.
!i(ple 3die*13 state(ents
Custo( errors and error triggers
9rror reporting
7asic 0rror Handling. Qsing the dieBfunction
The first example shows a simple script that opens a text file.
>?php:"ile
-
8/10/2019 Cara Pembuatan PHP Dasar
56/101
$arnin%# "open*2elco(e.txt1 U"unction."openV# "ailed to open strea(#No such "ile or director$ in 'we(fol"er'test.phpon line )
To a!oid that the user gets an error message like the one a"o!e% wetest if the file exist "efore we tr to access it.
>?phpi"*@"ile;exists*32elco(e.txt311 R die*37ile not "ound31= Selse R :"ile
-
8/10/2019 Cara Pembuatan PHP Dasar
57/101
error;level 8eOuired. !peci"ies the error report level "or the user-de"ined error.Must )e a value nu()er. !ee ta)le )elo2 "or possi)le error report levels
error;(essage 8eOuired. !peci"ies the error (essage "or the user-de"ined error
error;"ile ptional. !peci"ies the "ilena(e in 2hich the error occurred
error;line ptional. !peci"ies the line nu()er in 2hich the error occurrederror;context ptional. !peci"ies an arra$ containing ever$ varia)le% and their values%
in use 2hen the error occurred
0rror -eport le!els
These error report le!els are the different tpes of error the user$defined error handler can "e used for.
*alue &onstant Description
I 9;5'8N,N Non-"atal run-ti(e errors. 9xecution o" the script isnot halted
9;NT,C9 8un-ti(e notices. The script "ound so(ething that(ight )e an error% )ut could also happen 2henrunning a script nor(all$
IKB 9;6!98;9888 7atal user-generated error. This is li&e an 9;9888set )$ the progra((er using the PHP "unctiontrigger;error*1
KAI 9;6!98;5'8N,N Non-"atal user-generated 2arning. This is li&e an9;5'8N,N set )$ the progra((er using the PHP"unction trigger;error*1
AFIJ 9;6!98;NT,C9 6ser-generated notice. This is li&e an 9;NT,C9set )$ the progra((er using the PHP "unctiontrigger;error*1
JFGB 9;89C98'0L9;9888 Catcha)le "atal error. This is li&e an 9;9888 )utcan )e caught )$ a user de"ined handle *see alsoset;error;handler*11
AGA 9;'LL 'll errors and 2arnings% except level 9;!T8,CT*9;!T8,CT 2ill )e part o" 9;'LL as o" PHP B.F1
Now lets create a function to handle errors.
"unction custo(9rror*:errno% :errstr1 R echo 3>)9rror#>/) U:errnoV :errstr>)r /3= echo 39nding !cript3= die*1= S
-
8/10/2019 Cara Pembuatan PHP Dasar
58/101
The code a"o!e is a simple error handling function# When it istriggered% it gets the error le!el and an error message# )t then outputsthe error le!el and message and terminates the script#
Now that we ha!e created an error handling function we need to
decide when it should "e triggered#
Set 0rror Handler
The default error handler for PHP is the "uilt in error handler# We aregoing to make the function a"o!e the default error handler for theduration of the script#
)t is possi"le to change the error handler to appl for onl some errors%that wa the script can handle different errors in different was#Howe!er% in this example we are going to use our custom error handlerfor all errors.
set;error;handler*3custo(9rror31=
Since we want our custom function to handle all errors% thesetRerrorRhandlerB onl needed one parameter% a second parametercould "e added to specif an error le!el#
0xampleTesting the error handler " tring to output !aria"le that does notexist.
>?php//error handler "unction"unction custo(9rror*:errno% :errstr1 R echo 3>)9rror#>/) U:errnoV :errstr3= S
//set error handlerset;error;handler*3custo(9rror31=
//trigger errorecho*:test1=?
-
8/10/2019 Cara Pembuatan PHP Dasar
59/101
The output of the code a"o!e should "e something like this.
Error#UV 6nde"ined varia)le# test
Trigger an 0rror
)n a script where users can input data it is useful to trigger errorswhen an illegal input occurs# )n PHP% this is done " the triggerRerrorBfunction#
0xample
)n this example an error occurs if the DtestD !aria"le is "igger than DJD.
>?php:test
-
8/10/2019 Cara Pembuatan PHP Dasar
60/101
)n this example an 0RQS0-RW(-N)NV occurs if the DtestD !aria"le is"igger than DJD# )f an 0RQS0-RW(-N)NV occurs we will use ourcustom error handler and end the script.
>?php
//error handler "unction"unction custo(9rror*:errno% :errstr1 R echo 3>)9rror#>/) U:errnoV :errstr>)r /3= echo 39nding !cript3= die*1= S
//set error handlerset;error;handler*3custo(9rror3%9;6!98;5'8N,N1=
//trigger error:test
-
8/10/2019 Cara Pembuatan PHP Dasar
61/101
)n the example "elow we will send an e$mail with an error messageand end the script% if a specific error occurs.
>?php//error handler "unction
"unction custo(9rror*:errno% :errstr1 R echo 3>)9rror#>/) U:errnoV :errstr>)r /3= echo 35e)(aster has )een noti"ied3= error;log*39rror# U:errnoV :errstr3%A% 3so(eone^exa(ple.co(3%37ro(# 2e)(aster^exa(ple.co(31= S
//set error handlerset;error;handler*3custo(9rror3%9;6!98;5'8N,N1=
//trigger error:test
-
8/10/2019 Cara Pembuatan PHP Dasar
62/101
What is an 0xception
With PHP < came a new o"8ect oriented wa of dealing with errors#
0xception handling is used to change the normal flow of the code execution if a
specified error Bexceptional condition occurs# This condition is called an exception#
This is what normall happens when an exception is triggered.
The current code state is sa!ed The code execution will switch to a predefined Bcustom exception handler
function /epending on the situation% the handler ma then resume the execution from
the sa!ed code state% terminate the script execution or continue the scriptfrom a different location in the code
We will show different error handling methods.
7asic use of 0xceptions Creating a custom exception handler &ultiple exceptions -e$throwing an exception Setting a top le!el exception handler
Note:0xceptions should onl "e used with error conditions% and should not "e usedto 8ump to another place in the code at a specified point#
7asic Qse of 0xceptionsWhen an exception is thrown% the code following it will not "e executed% and PHP willtr to find the matching DcatchD "lock#
)f an exception is not caught% a fatal error will "e issued with an DQncaught0xceptionD message#
2ets tr to throw an exception without catching it.
@9php==create function with an exceptionfunction checkNumBnum"er Y ifBnum"erAJ Y throw new 0xceptionBDGalue must "e J or "elowDE Z return trueE Z
-
8/10/2019 Cara Pembuatan PHP Dasar
63/101
-
8/10/2019 Cara Pembuatan PHP Dasar
64/101
Z9A
The code a"o!e will get an error like this.
&essage. Galue must "e J or "elow
0xample explained.
The code a"o!e throws an exception and catches it.
J# The checkNumB function is created# )t checks if a num"er is greater than J#)f it is% an exception is thrown
K# The checkNumB function is called in a DtrD "lock3# The exception within the checkNumB function is thrown\# The DcatchD "lock retri!es the exception and creates an o"8ect Be containing
the exception informationuite simple# We simpl create a special classwith functions that can "e called when an exception occurs in PHP# The class must "ean extension of the exception class#
The custom exception class inherits the properties from PHP's exception class andou can add custom functions to it#
2ets create an exception class.
@9phpclass custom0xception extends 0xception Y pu"lic function error&essageB Y ==error message
error&sg I '0rror on line '#this$Aget2ineB#' in '#this$Aget1ileB #'. @"A'#this$Aget&essageB#'@="A is not a !alid 0$&ail address'E return error&sgE Z Z
email I Dsomeone]example###comDE
tr
-
8/10/2019 Cara Pembuatan PHP Dasar
65/101
Y ==check if ifBfilterR!arBemail% 1)2T0-RG(2)/(T0R0&()2 III 1(2S0 Y ==throw exception if email is not !alid throw new custom0xceptionBemailE
Z Z
catch Bcustom0xception e Y ==displa custom message echo e$Aerror&essageBE Z9A
The new class is a cop of the old exception class with an addition of theerror&essageB function# Since it is a cop of the old class% and it inherits theproperties and methods from the old class% we can use the exception class methodslike get2ineB and get1ileB and get&essageB#
0xample explained.
The code a"o!e throws an exception and catches it with a custom exception class.
J# The custom0xceptionB class is created as an extension of the old exceptionclass# This wa it inherits all methods and properties from the old exceptionclass
K# The error&essageB function is created# This function returns an errormessage if an e$mail address is in!alid
3# The email !aria"le is set to a string that is not a !alid e$mail address\# The DtrD "lock is executed and an exception is thrown since the e$mailaddress is in!alid
-
8/10/2019 Cara Pembuatan PHP Dasar
66/101
error&sg I '0rror on line '#this$Aget2ineB#' in '#this$Aget1ileB#'. @"A'#this$Aget&essageB#'@="A is not a !alid 0$&ail address'Ereturn error&sgEZZ
email I Dsomeone]example#comDE
tr Y ==check if ifBfilterR!arBemail% 1)2T0-RG(2)/(T0R0&()2 III 1(2S0 Y ==throw exception if email is not !alid throw new custom0xceptionBemailE Z ==check for DexampleD in mail address ifBstrposBemail% DexampleD ,II 1(2S0 Y throw new 0xceptionBDemail is an example e$mailDE Z Z
catch Bcustom0xception e Y echo e$Aerror&essageBE Z
catchB0xception e Y echo e$Aget&essageBE
Z9A
0xample explained.
The code a"o!e tests two conditions and throws an exception if an of the conditionsare not met.
J# The custom0xceptionB class is created as an extension of the old exceptionclass# This wa it inherits all methods and properties from the old exceptionclass
K# The error&essageB function is created# This function returns an error
message if an e$mail address is in!alid3# The email !aria"le is set to a string that is a !alid e$mail address% "utcontains the string DexampleD
\# The DtrD "lock is executed and an exception is not thrown on the firstcondition
-
8/10/2019 Cara Pembuatan PHP Dasar
67/101
)f there was no custom0xception catch% onl the "ase exception catch% the exceptionwould "e handled there
-e$throwing 0xceptions
Sometimes% when an exception is thrown% ou ma wish to handle it differentl thanthe standard wa# )t is possi"le to throw an exception a second time within a DcatchD"lock#
( script should hide sstem errors from users# Sstem errors ma "e important forthe coder% "ut is of no interest to the user# To make things easier for the user ou canre$throw the exception with a user friendl message.
@9phpclass custom0xception extends 0xception Y
pu"lic function error&essageB Y ==error message error&sg I this$Aget&essageB#' is not a !alid 0$&ail address#'E return error&sgE Z Z
email I Dsomeone]example#comDE
tr Y
tr Y ==check for DexampleD in mail address ifBstrposBemail% DexampleD ,II 1(2S0 Y ==throw exception if email is not !alid throw new 0xceptionBemailE Z Z catchB0xception e Y ==re$throw exception throw new custom0xceptionBemailE
Z Z
catch Bcustom0xception e Y ==displa custom message echo e$Aerror&essageBE Z9A
-
8/10/2019 Cara Pembuatan PHP Dasar
68/101
0xample explained.
The code a"o!e tests if the email$address contains the string DexampleD in it% if itdoes% the exception is re$thrown.
J# The custom0xceptionB class is created as an extension of the old exceptionclass# This wa it inherits all methods and properties from the old exceptionclass
K# The error&essageB function is created# This function returns an errormessage if an e$mail address is in!alid
3# The email !aria"le is set to a string that is a !alid e$mail address% "utcontains the string DexampleD
\# The DtrD "lock contains another DtrD "lock to make it possi"le to re$throwthe exception
-
8/10/2019 Cara Pembuatan PHP Dasar
69/101
Code ma "e surrounded in a tr "lock% to help catch potential exceptions 0ach tr "lock or DthrowD must ha!e at least one corresponding catch "lock &ultiple catch "locks can "e used to catch different classes of exceptions 0xceptions can "e thrown Bor re$thrown in a catch "lock within a tr "lock
( simple rule. )f ou throw something% ou ha!e to catch it#
PHP 1ilter
Pre!ious Next Chapter
PHP filters are used to !alidate and filter data coming from insecuresources% like user input#
What is a PHP 1ilter9
( PHP filter is used to !alidate and filter data coming from insecure sources#
To test% !alidate and filter user input or custom data is an important part of an we"application#
The PHP filter extension is designed to make data filtering easier and >uicker#
Wh use a 1ilter9(lmost all we" applications depend on external input# Qsuall this comes from a useror another application Blike a we" ser!ice# 7 using filters ou can "e sure ourapplication gets the correct input tpe#
,o shol always filter all e'ternal ata!
)nput filtering is one of the most important application securit issues#
What is external data9
)nput data from a form Cookies We" ser!ices data Ser!er !aria"les /ata"ase >uer results
http://www.w3schools.com/php/php_exception.asphttp://www.w3schools.com/php/php_mysql_intro.asphttp://www.w3schools.com/php/php_exception.asphttp://www.w3schools.com/php/php_mysql_intro.asp -
8/10/2019 Cara Pembuatan PHP Dasar
70/101
1unctions and 1ilters
To filter a !aria"le% use one of the following filter functions.
filterR!arB $ 1ilters a single !aria"le with a specified filter
filterR!arRarraB $ 1ilter se!eral !aria"les with the same or different filters filterRinput $ Vet one input !aria"le and filter it filterRinputRarra $ Vet se!eral input !aria"les and filter them with the same
or different filters
)n the example "elow% we !alidate an integer using the filterR!arB function.
@9phpint I JK3E
ifB,filterR!arBint% 1)2T0-RG(2)/(T0R)NT Y
echoBD)nteger is not !alidDE Zelse Y echoBD)nteger is !alidDE Z9A
The code a"o!e uses the D1)2T0-RG(2)/(T0R)NTD filter to filter the !aria"le# Sincethe integer is !alid% the output of the code a"o!e will "e. D)nteger is !alidD#
)f we tr with a !aria"le that is not an integer Blike DJK3a"cD% the output will "e.
D)nteger is not !alidD#1or a complete list of functions and filters% !isit our PHP 1ilter -eference#
Galidating and Saniti+ing
There are two kinds of filters.
Galidating filters.
(re used to !alidate user input Strict format rules Blike Q-2 or 0$&ail !alidating -eturns the expected tpe on success or 1(2S0 on failure
Saniti+ing filters.
(re used to allow or disallow specified characters in a string No data format rules
http://www.w3schools.com/php/php_ref_filter.asphttp://www.w3schools.com/php/php_ref_filter.asp -
8/10/2019 Cara Pembuatan PHP Dasar
71/101
(lwas return the string
?ptions and 1lags
?ptions and flags are used to add additional filtering options to the specified filters#
/ifferent filters ha!e different options and flags#
)n the example "elow% we !alidate an integer using the filterR!arB and theDminRrangeD and DmaxRrangeD options.
@9php!arI3E
intRoptions I arraBDoptionsDIAarra B DminRrangeDIA% DmaxRrangeDIAK
-
8/10/2019 Cara Pembuatan PHP Dasar
72/101
Then we filter the input data using the filterRinputB function#
)n the example "elow% the input !aria"le DemailD is sent to the PHP page.
@9phpifB,filterRhasR!arB)NPQTRV0T% DemailD
Y echoBD)nput tpe does not existDE Zelse Y if B,filterRinputB)NPQTRV0T% DemailD% 1)2T0-RG(2)/(T0R0&()2 Y echo D0$&ail is not !alidDE Z else Y echo D0$&ail is !alidDE
Z Z9A
0xample 0xplained
The example a"o!e has an input Bemail sent to it using the DV0TD method.
J# Check if an DemailD input !aria"le of the DV0TD tpe existK# )f the input !aria"le exists% check if it is a !alid e$mail address
Saniti+e )nput
2et's tr cleaning up an Q-2 sent from a form#
1irst we confirm that the input data we are looking for exists#
Then we saniti+e the input data using the filterRinputB function#
)n the example "elow% the input !aria"le DurlD is sent to the PHP page.
@9php
ifB,filterRhasR!arB)NPQTRP?ST% DurlD Y echoBD)nput tpe does not existDE Zelse Y url I filterRinputB)NPQTRP?ST%DurlD% 1)2T0-RS(N)T)40RQ-2E
Z
-
8/10/2019 Cara Pembuatan PHP Dasar
73/101
9A
0xample 0xplained
The example a"o!e has an input Burl sent to it using the DP?STD method.
J# Check if the DurlD input of the DP?STD tpe existsK# )f the input !aria"le exists% saniti+e Btake awa in!alid characters and store it
in the url !aria"le
)f the input !aria"le is a string like this Dhttp.==www#W3^^Sch__ools#com=D% the url!aria"le after the saniti+ing will look like this.
http.==www#W3Schools#com=
1ilter &ultiple )nputs
( form almost alwas consist of more than one input field# To a!oid calling thefilterR!ar or filterRinput functions o!er and o!er% we can use the filterR!arRarra orthe filterRinputRarra functions#
)n this example we use the filterRinputRarraB function to filter three V0T !aria"les#The recei!ed V0T !aria"les is a name% an age and an e$mail address.
@9phpfilters I arra B DnameD IA arra B DfilterDIA1)2T0-RS(N)T)40RST-)NV % DageD IA arra B DfilterDIA1)2T0-RG(2)/(T0R)NT% DoptionsDIAarra B DminRrangeDIAJ% DmaxRrangeDIAJK %
DemailDIA 1)2T0-RG(2)/(T0R0&()2% E
result I filterRinputRarraB)NPQTRV0T% filtersE
if B,resultDageD Y echoBD(ge must "e a num"er "etween J and JK#@"r =ADE Z
-
8/10/2019 Cara Pembuatan PHP Dasar
74/101
elseifB,resultDemailD Y echoBD0$&ail is not !alid#@"r =ADE Zelse Y
echoBDQser input is !alidDE Z9A
0xample 0xplained
The example a"o!e has three inputs Bname% age and email sent to it using theDV0TD method.
J# Set an arra containing the name of input !aria"les and the filters used onthe specified input !aria"les
K# Call the filterRinputRarraB function with the V0T input !aria"les and the
arra we 8ust set3# Check the DageD and DemailD !aria"les in the result !aria"le for in!alidinputs# B)f an of the input !aria"les are in!alid% that input !aria"le will "e1(2S0 after the filterRinputRarraB function
The second parameter of the filterRinputRarraB function can "e an arra or a singlefilter )/#
)f the parameter is a single filter )/ all !alues in the input arra are filtered " thespecified filter#
)f the parameter is an arra it must follow these rules.
&ust "e an associati!e arra containing an input !aria"le as an arra ke Blikethe DageD input !aria"le
The arra !alue must "e a filter )/ or an arra specifing the filter% flags andoptions
Qsing 1ilter Call"ack
)t is possi"le to call a user defined function and use it as a filter using the1)2T0-RC(227(C6 filter# This wa% we ha!e full control of the data filtering#
5ou can create our own user defined function or use an existing PHP function
The function ou wish to use to filter is specified the same wa as an option isspecified# )n an associati!e arra with the name DoptionsD
)n the example "elow% we use a user created function to con!ert all DRD towhitespaces.
-
8/10/2019 Cara Pembuatan PHP Dasar
75/101
@9phpfunction con!ertSpaceBstringYreturn strRreplaceBDRD% D D% stringEZ
string I DPeterRisRaRgreatRgu,DE
echo filterR!arBstring% 1)2T0-RC(227(C6%arraBDoptionsDIADcon!ertSpaceDE9A
The result from the code a"o!e should look like this.
Peter is a great gu,
0xample 0xplained
The example a"o!e con!erts all DRD to whitespaces.
J# Create a function to replace DRD to whitespacesK# Call the filterR!arB function with the 1)2T0-RC(227(C6 filter and an arra
containing our function
PHP &S*2 )ntroduction Previous Next Chapter
M$!+L is the (ost popular open-source data)ase s$ste(.
What is &S*29
&S*2 is a data"ase#
The data in &S*2 is stored in data"ase o"8ects called ta"les#
( ta"le is a collections of related data entries and it consists ofcolumns and rows#
/ata"ases are useful when storing information categoricall# (compan ma ha!e a data"ase with the following ta"les. D0mploeesD%DProductsD% DCustomersD and D?rdersD#
http://www.w3schools.com/php/php_filter.asphttp://www.w3schools.com/php/php_mysql_connect.asphttp://www.w3schools.com/php/php_filter.asphttp://www.w3schools.com/php/php_mysql_connect.asp -
8/10/2019 Cara Pembuatan PHP Dasar
76/101
/ata"ase Ta"les
( data"ase most often contains one or more ta"les# 0ach ta"le is
identified " a name Be#g# DCustomersD or D?rdersD# Ta"les containrecords Brows with data#
7elow is an example of a ta"le called DPersonsD.
,astName -irstName A""ress &ity
Hansen la Ti(oteivn AF !andnes
!vendson Tove 0orgvn I4 !andnes
Pettersen Yari !torgt IF !tavanger
The ta"le a"o!e contains three records Bone for each person and fourcolumns B2astName% 1irstName% (ddress% and Cit#
*ueries
( >uer is a >uestion or a re>uest#
With &S*2% we can >uer a data"ase for specific information and
ha!e a recordset returned#
2ook at the following >uer.
!9L9CT LastNa(e 78M Persons
The >uer a"o!e selects all the data in the D2astNameD column fromthe DPersonsD ta"le% and will return a recordset like this.
,astName
Hansen
!vendson
Pettersen
/ownload &S*2 /ata"ase
-
8/10/2019 Cara Pembuatan PHP Dasar
77/101
)f ou don't ha!e a PHP ser!er with a &S*2 /ata"ase% ou candownload &S*2 for free here.http.==www#ms>l#com=downloads=index#html
1acts ("out &S*2 /ata"ase
?ne great thing a"out &S*2 is that it can "e scaled down to supportem"edded data"ase applications# Perhaps it is "ecause of thisreputation that man people "elie!e that &S*2 can onl handle smallto medium$si+ed sstems#
The truth is that &S*2 is the de$facto standard data"ase for we"sites that support huge !olumes of "oth data and end users Blike1riendster% 5ahoo% Voogle#
2ook at http.==www#ms>l#com=customers=for an o!er!iew ofcompanies using &S*2#
PHP &S*2 Connect to a /ata"ase Previous Next Chapter
The "ree M$!+L data)ase is ver$ o"ten used 2ith PHP.
Create a Connection to a &S*2 /ata"ase
7efore ou can access data in a data"ase% ou must create aconnection to the data"ase#
)n PHP% this is done with the ms>lRconnectB function#
Syntax($sOl;connect*serverna(e%userna(e%pass2ord1=
Parameter Description
serverna(e ptional. !peci"ies the server to connect to. e"ault value is3localhost#44FB3
userna(e ptional. !peci"ies the userna(e to log in 2ith. e"ault value is the
http://www.mysql.com/downloads/index.htmlhttp://www.mysql.com/customers/http://www.w3schools.com/php/php_mysql_intro.asphttp://www.w3schools.com/php/php_mysql_create.asphttp://www.mysql.com/downloads/index.htmlhttp://www.mysql.com/customers/http://www.w3schools.com/php/php_mysql_intro.asphttp://www.w3schools.com/php/php_mysql_create.asp -
8/10/2019 Cara Pembuatan PHP Dasar
78/101
na(e o" the user that o2ns the server process
pass2ord ptional. !peci"ies the pass2ord to log in 2ith. e"ault is 33
Note:There are more a!aila"le parameters% "ut the ones listed a"o!eare the most important# Gisit our full PHP &S*2 -eferencefor moredetails#
Example
)n the following example we store the connection in a !aria"le Bconfor later use in the script# The DdieD part will "e executed if theconnection fails.
>?php:con < ($sOl;connect*3localhost3%3peter3%3a)cAI431=
i" *@:con1 R die*WCould not connect# W . ($sOl;error*11= S
// so(e code?
Closing a Connection
The connection will "e closed automaticall when the script ends# Toclose the connection "efore% use the ms>lRcloseB function.
>?php:con < ($sOl;connect*3localhost3%3peter3%3a)cAI431=i" *@:con1 R die*WCould not connect# W . ($sOl;error*11= S
// so(e code
($sOl;close*:con1=?
http://www.w3schools.com/php/php_ref_mysql.asphttp://www.w3schools.com/php/php_ref_mysql.asp -
8/10/2019 Cara Pembuatan PHP Dasar
79/101
PHP &S*2 Create /ata"ase andTa"les
Previous Next Chapter
' data)ase holds one or (ultiple ta)les.
Create a /ata"ase
The C-0(T0 /(T(7(S0 statement is used to create a data"ase in&S*2#
Syntax
C89'T9 'T'0'!9 data)ase;na(e
To learn (ore a)out !+L% please visit our !+L tutorial.
To get PHP to execute the statement a"o!e we must use thems>lR>uerB function# This function is used to send a >uer orcommand to a &S*2 connection#
Example
The following example creates a data"ase called DmRd"D.
>?php:con < ($sOl;connect*3localhost3%3peter3%3a)cAI431=i" *@:con1 R die*WCould not connect# W . ($sOl;error*11= S
i" *($sOl;Ouer$*3C89'T9 'T'0'!9 ($;d)3%:con11 R echo 3ata)ase created3= Selse R echo 39rror creating data)ase# 3 . ($sOl;error*1= S
http://www.w3schools.com/php/php_mysql_connect.asphttp://www.w3schools.com/php/php_mysql_insert.asphttp://www.w3schools.com/sql/default.asphttp://www.w3schools.com/php/php_mysql_connect.asphttp://www.w3schools.com/php/php_mysql_insert.asphttp://www.w3schools.com/sql/default.asp -
8/10/2019 Cara Pembuatan PHP Dasar
80/101
($sOl;close*:con1=?
Create a Ta"leThe C-0(T0 T(720 statement is used to create a ta"le in &S*2#
Syntax
C89'T9 T'0L9 ta)le;na(e*colu(n;na(eA data;t$pe%colu(n;na(eI data;t$pe%colu(n;na(e4 data;t$pe%
....1
To learn more a"out S*2% please !isit our S*2 tutorial#
We must add the C-0(T0 T(720 statement to the ms>lR>uerBfunction to execute the command#
Example
The following example creates a ta"le named DPersonsD% with threecolumns# The column names will "e D1irstNameD% D2astNameD andD(geD.
>?php:con < ($sOl;connect*3localhost3%3peter3%3a)cAI431=i" *@:con1 R die*WCould not connect# W . ($sOl;error*11= S
// Create data)asei" *($sOl;Ouer$*3C89'T9 'T'0'!9 ($;d)3%:con11 R echo 3ata)ase created3= Selse R echo 39rror creating data)ase# 3 . ($sOl;error*1=
http://www.w3schools.com/sql/default.asphttp://www.w3schools.com/sql/default.asp -
8/10/2019 Cara Pembuatan PHP Dasar
81/101
S
// Create ta)le($sOl;select;d)*3($;d)3% :con1=:sOl < 3C89'T9 T'0L9 Persons
*7irstNa(e varchar*AK1%LastNa(e varchar*AK1%'ge int13=
// 9xecute Ouer$($sOl;Ouer$*:sOl%:con1=
($sOl;close*:con1=?
-mportant:( data"ase must "e selected "efore a ta"le can "ecreated# The data"ase is selected with the ms>lRselectRd"B function#
Note:When ou create a data"ase field of tpe !archar% ou mustspecif the maximum length of the field% e#g# !archarBJuel identif the rows in a ta"le# 0achprimar ke !alue must "e uni>ue within the ta"le# 1urthermore% theprimar ke field cannot "e null "ecause the data"ase engine re>uiresa !alue to locate the record#
The following example sets the person)/ field as the primar ke field#The primar ke field is often an )/ num"er% and is often used with the(QT?R)NC-0&0NT setting# (QT?R)NC-0&0NT automaticall increasesthe !alue of the field " J each time a new record is added# To ensurethat the primar ke field cannot "e null% we must add the N?T NQ22setting to the field#
http://www.w3schools.com/sql/sql_datatypes.asphttp://www.w3schools.com/sql/sql_datatypes.asp -
8/10/2019 Cara Pembuatan PHP Dasar
82/101
Example
:sOl < 3C89'T9 T'0L9 Persons*person, int NT N6LL '6T;,NC89M9NT%P8,M'8[ Y9[*person,1%
7irstNa(e varchar*AK1%LastNa(e varchar*AK1%'ge int13=
($sOl;Ouer$*:sOl%:con1=
PHP &S*2 )nsert )nto Previous Next Chapter
The ,N!98T ,NT state(ent is used to insert ne2 records in a ta)le.
)nsert /ata )nto a /ata"ase Ta"le
The )NS0-T )NT? statement is used to add new records to a data"aseta"le#
Syntax
)t is possi"le to write the )NS0-T )NT? statement in two forms#
The first form doesn't specif the column names where the data will "einserted% onl their !alues.
,N!98T ,NT ta)le;na(e'L69! *valueA% valueI% value4%...1
The second form specifies "oth the column names and the !alues to "einserted.
,N!98T ,NT ta)le;na(e *colu(nA% colu(nI% colu(n4%...1'L69! *valueA% valueI% value4%...1
To learn (ore a)out !+L% please visit our !+L tutorial.
http://www.w3schools.com/php/php_mysql_create.asphttp://www.w3schools.com/php/php_mysql_select.asphttp://www.w3schools.com/sql/default.asphttp://www.w3schools.com/php/php_mysql_create.asphttp://www.w3schools.com/php/php_mysql_select.asphttp://www.w3schools.com/sql/default.asp -
8/10/2019 Cara Pembuatan PHP Dasar
83/101
To get PHP to execute the statements a"o!e we must use thems>lR>uerB function# This function is used to send a >uer orcommand to a &S*2 connection#
Example
)n the pre!ious chapter we created a ta"le named DPersonsD% withthree columnsE D1irstnameD% D2astnameD and D(geD# We will use thesame ta"le in this example# The following example adds two newrecords to the DPersonsD ta"le.
>?php:con < ($sOl;connect*3localhost3%3peter3%3a)cAI431=i" *@:con1 R die*WCould not connect# W . ($sOl;error*11=
S
($sOl;select;d)*3($;d)3% :con1=
($sOl;Ouer$*3,N!98T ,NT Persons *7irstNa(e% LastNa(e% 'ge1'L69! *WPeterW% Wri""inW% W4KW131=
($sOl;Ouer$*3,N!98T ,NT Persons *7irstNa(e% LastNa(e% 'ge1'L69! *WlennW% W+uag(ireW% W44W131=
($sOl;close*:con1=
?
)nsert /ata 1rom a 1orm )nto a /ata"ase
Now we will create an HT&2 form that can "e used to add new recordsto the DPersonsD ta"le#
Here is the HT&2 form.
>ht(l>)od$
>"or( action
-
8/10/2019 Cara Pembuatan PHP Dasar
84/101
>input t$pe/"or(
>/)od$>/ht(l
When a user clicks the su"mit "utton in the HT&2 form in the examplea"o!e% the form data is sent to Dinsert#phpD#
The Dinsert#phpD file connects to a data"ase% and retrie!es the !aluesfrom the form with the PHP RP?ST !aria"les#
Then% the ms>lR>uerB function executes the )NS0-T )NT?statement% and a new record will "e added to the DPersonsD ta"le#
Here is the Dinsert#phpD page.
>?php:con < ($sOl;connect*3localhost3%3peter3%3a)cAI431=i" *@:con1 R die*WCould not connect# W . ($sOl;error*11= S
($sOl;select;d)*3($;d)3% :con1=
:sOl
-
8/10/2019 Cara Pembuatan PHP Dasar
85/101
Select /ata 1rom a /ata"ase Ta"le
The S020CT statement is used to select data from a data"ase#
Syntax
!9L9CT colu(n;na(e*s178M ta)le;na(e
To learn more a"out S*2% please !isit our S*2 tutorial#
To get PHP to execute the statement a"o!e we must use thems>lR>uerB function# This function is used to send a >uer orcommand to a &S*2 connection#
Example
The following example selects all the data stored in the DPersonsD ta"leBThe F character selects all the data in the ta"le.
>?php:con < ($sOl;connect*3localhost3%3peter3%3a)cAI431=i" *@:con1 R die*WCould not connect# W . ($sOl;error*11=
S
($sOl;select;d)*3($;d)3% :con1=
:result < ($sOl;Ouer$*3!9L9CT 78M Persons31=
2hile*:ro2 < ($sOl;"etch;arra$*:result11 R echo :ro2UW7irstNa(eWV . 3 3 . :ro2UWLastNa(eWV= echo 3>)r /3= S
($sOl;close*:con1=?
The example a"o!e stores the data returned " the ms>lR>uerBfunction in the result !aria"le#
http://www.w3schools.com/sql/default.asphttp://www.w3schools.com/sql/default.asp -
8/10/2019 Cara Pembuatan PHP Dasar
86/101
Next% we use the ms>lRfetchRarraB function to return the first rowfrom the recordset as an arra# 0ach call to ms>lRfetchRarraBreturns the next row in the recordset# The while loop loops through allthe records in the recordset# To print the !alue of each row% we use thePHP row !aria"le Brow'1irstName' and row'2astName'#
The output of the code a"o!e will "e.
Peter ri""inlenn +uag(ire
/ispla the -esult in an HT&2 Ta"le
The following example selects the same data as the example a"o!e%"ut will displa the data in an HT&2 ta"le.
>?php:con < ($sOl;connect*3localhost3%3peter3%3a)cAI431=i" *@:con1 R die*WCould not connect# W . ($sOl;error*11= S
($sOl;select;d)*3($;d)3% :con1=
:result < ($sOl;Ouer$*3!9L9CT 78M Persons31=
echo >ta)le )orderth7irstna(e>/th>thLastna(e>/th>/tr3=
2hile*:ro2 < ($sOl;"etch;arra$*:result11 R echo 3>tr3=
echo 3>td3 . :ro2UW7irstNa(eWV . 3>/td3= echo 3>td3 . :ro2UWLastNa(eWV . 3>/td3= echo 3>/tr3= Secho 3>/ta)le3=
($sOl;close*:con1=?
-
8/10/2019 Cara Pembuatan PHP Dasar
87/101
The output of the code a"o!e will "e.
-irstname ,astname
lenn +uag(ire
Peter ri""in
PHP &S*2 The Where Clause Previous Next Chapter
The 5H989 clause is used to "ilter records.
The WH0-0 clauseThe WH0-0 clause is used to extract onl those records that fulfill aspecified criterion#
Syntax
!9L9CT colu(n;na(e*s178M ta)le;na(e5H989 colu(n;na(e operator value
To learn more a"out S*2% please !isit our S*2 tutorial#
To get PHP to execute the statement a"o!e we must use thems>lR>uerB function# This function is used to send a >uer orcommand to a &S*2 connection#
Example
The following example selects all rows from the DPersonsD ta"le whereD1irstNameI'Peter'.
>?php:con < ($sOl;connect*3localhost3%3peter3%3a)cAI431=i" *@:con1 R die*WCould not connect# W . ($sOl;error*11= S
($sOl;select;d)*3($;d)3% :con1=
http://www.w3schools.com/php/php_mysql_select.asphttp://www.w3schools.com/php/php_mysql_order_by.asphttp://www.w3schools.com/sql/default.asphttp://www.w3schools.com/php/php_mysql_select.asphttp://www.w3schools.com/php/php_mysql_order_by.asphttp://www.w3schools.com/sql/default.asp -
8/10/2019 Cara Pembuatan PHP Dasar
88/101
:result < ($sOl;Ouer$*3!9L9CT 78M Persons5H989 7irstNa(elRconnectBDlocalhostD%DpeterD%Da"cJK3DEif B,con
http://www.w3schools.com/php/php_mysql_where.asphttp://www.w3schools.com/php/php_mysql_update.asphttp://www.w3schools.com/sql/default.asphttp://www.w3schools.com/php/php_mysql_where.asphttp://www.w3schools.com/php/php_mysql_update.asphttp://www.w3schools.com/sql/default.asp -
8/10/2019 Cara Pembuatan PHP Dasar
89/101
Y dieB'Could not connect. ' # ms>lRerrorBE Z
ms>lRselectRd"BDmRd"D% conE
result I ms>lR>uerBDS020CT F 1-?& Persons ?-/0- 75 ageDE
whileBrow I ms>lRfetchRarraBresult Y echo row'1irstName'E echo D D # row'2astName'E echo D D # row'(ge'E echo D@"r =ADE Z
ms>lRcloseBconE9A
The output of the code a"o!e will "e.
Vlenn *uagmire 33Peter Vriffin 3ual.
S020CT columnRnameBs1-?& ta"leRname?-/0- 75 columnJ% columnK
PHP &S*2 Qpdate
Pre!ious Next Chapter
The 6P'T9 state(ent is used to (odi"$ data in a ta)le.
Qpdate /ata )n a /ata"ase
The QP/(T0 statement is used to update existing records in a ta"le#
http://www.w3schools.com/php/php_mysql_order_by.asphttp://www.w3schools.com/php/php_mysql_delete.asphttp://www.w3schools.com/php/php_mysql_order_by.asphttp://www.w3schools.com/php/php_mysql_delete.asp -
8/10/2019 Cara Pembuatan PHP Dasar
90/101
Syntax
QP/(T0 ta"leRnameS0T columnJI!alue% columnKI!alueK%###WH0-0 someRcolumnIsomeR!alue
Note:Notice the WH0-0 clause in the QP/(T0 sntax# The WH0-0 clause specifies
which record or records that should "e updated# )f ou omit the WH0-0 clause% allrecords will "e updated,
To learn more a"out S*2% please !isit our S*2 tutorial#
To get PHP to execute the statement a"o!e we must use the ms>lR>uerB function#This function is used to send a >uer or command to a &S*2 connection#
Example
0arlier in the tutorial we created a ta"le named DPersonsD# Here is how it looks.
&irstName LastName Age
Peter Vriffin 3lRerrorBE Z
ms>lRselectRd"BDmRd"D% conE
ms>lR>uerBDQP/(T0 Persons S0T (ge I '3L'WH0-0 1irstName I 'Peter' (N/ 2astName I 'Vriffin'DE
ms>lRcloseBconE9A
(fter the update% the DPersonsD ta"le will look like this.
&irstName LastName Age
Peter Vriffin 3L
Vlenn *uagmire 33
PHP &S*2 /elete
http://www.w3schools.com/sql/default.asphttp://www.w3schools.com/sql/default.asp -
8/10/2019 Cara Pembuatan PHP Dasar
91/101
Previous Next Chapter
The 9L9T9 state(ent is used to delete records in a ta)le.
/elete /ata )n a /ata"ase
The /020T0 1-?& statement is used to delete records from adata"ase ta"le#
Syntax
9L9T9 78M ta)le;na(e5H989 so(e;colu(n < so(e;value
Note#Notice the 5H989 clause in the 9L9T9 s$ntax. The 5H989 clause speci"ies2hich record or records that should )e deleted. ," $ou o(it the 5H989 clause% allrecords 2ill )e deleted@
To learn more a"out S*2% please !isit our S*2 tutorial#
To get PHP to execute the statement a"o!e we must use thems>lR>uerB function# This function is used to send a >uer orcommand to a &S*2 connection#
Example
2ook at the following DPersonsD ta"le.
-irstName ,astName A%e
Peter ri""in 4K
lenn +uag(ire 44
The following example deletes all the records in the DPersonsD ta"lewhere 2astNameI'Vriffin'.
>?php:con < ($sOl;connect*3localhost3%3peter3%3a)cAI431=i" *@:con1 R die*WCould not connect# W . ($sOl;error*11= S
http://www.w3schools.com/php/php_mysql_update.asphttp://www.w3schools.com/php/php_db_odbc.asphttp://www.w3schools.com/sql/default.asphttp://www.w3schools.com/php/php_mysql_update.asphttp://www.w3schools.com/php/php_db_odbc.asphttp://www.w3schools.com/sql/default.asp -
8/10/2019 Cara Pembuatan PHP Dasar
92/101
($sOl;select;d)*3($;d)3% :con1=
($sOl;Ouer$*39L9T9 78M Persons 5H989 LastNa(e
-
8/10/2019 Cara Pembuatan PHP Dasar
93/101
Connecting to an ?/7C
The od"cRconnectB function is used to connect to an ?/7C data
source# The function takes four parameters. the data source name%username% password% and an optional cursor tpe#
The od"cRexecB function is used to execute an S*2 statement#
Example
The following example creates a connection to a /SN called northwind%with no username and no password# )t then creates an S*2 andexecutes it.
:conn
-
8/10/2019 Cara Pembuatan PHP Dasar
94/101
The code line "elow returns the !alue of a field calledDCompanNameD.
:co(pna(e/td3= echo 3>td:conna(e>/td>/tr3= Sod)c;close*:conn1=echo 3>/ta)le3=?
-
8/10/2019 Cara Pembuatan PHP Dasar
95/101
>/)od$>/ht(l
PHP &2 0xpat Parser Pre!ious Next Chapter
The )uilt-in 9xpat parser (a&es it possi)le to process XML docu(ents in PHP.
What is &29
&2 is used to descri"e data and to focus on what data is# (n &2 file descri"es the structureof the data#
)n &2% no tags are predefined# 5ou must define our own tags#
)f ou want to learn more a"out &2% please !isit our &2 tutorial#
What is 0xpat9
To read and update $ create and manipulate $ an &2 document% ou will need an &2 parser#
There are two "asic tpes of &2 parsers.
Tree$"ased parser. This parser transforms an &2 document into a tree structure# )tanal+es the whole document% and pro!ides access to the tree elements# e#g# the/ocument ?"8ect &odel B/?&
0!ent$"ased parser. Giews an &2 document as a series of e!ents# When a specifice!ent occurs% it calls a function to handle it
The 0xpat parser is an e!ent$"ased parser#
0!ent$"ased parsers focus on the content of the &2 documents% not their structure# 7ecauseof this% e!ent$"ased parsers can access data faster than tree$"ased parsers#
2ook at the following &2 fraction.
@fromA;ani@=fromA
(n e!ent$"ased parser reports the &2 a"o!e as a series of three e!ents.
Start element. from Start C/(T( se