You are on page 1of 136

PHP Guide Book

Moe Myint Shein

PHP GUIDE BOOK


First Edition
Moe Myint Shein

Youth Dreams

PHP Guide Book

Moe Myint Shein

Part (I)

Part

(II)

First edition

Second edition

First Edition

Chapter

PHP

Web Developer

PHP

Programming

..code

run

code

w3schools.com reference

moemyintsheinster@gmail.com

www.moemyintshein.com

Youth Dreams

PHP Guide Book

Moe Myint Shein

Contents at a Glance

Chapter 1

Introducing PHP

Chpater 2

The Building Blocks of PHP

Chapter 3

Flow Control Functoins in PHP

14

Chapter 4

Working With Functions and Forms

25

Chapter 5

PHP Date, Include, File Handling & Some PHP Advaced

32

Chapter 6

PHP and AJAX

54

Chapter 7

PHP MyAdmin Basic

74

Chapter 8

PHP and Database

83

Chapter 9

XML and PHP

97

Chatper 10 Exception Handling and Filter in PHP

124

Conclusion

136

Youth Dreams

PHP Guide Book

Moe Myint Shein

Chapter 1 Introducing PHP


What is PHP?
PHP
dynamic web pages

scripting language

PHP

web

scripts


stand

alone

application

application

PHP

) PHP


Rasmus
Lerdorf

1994
PHP

Personal Home Page


Rasmus Lerdorf

PHP: Hypertext Preprocessor


PHP

programming language

PHP

THE
PHP GROUP maintain

PHP PHP License

free
software


PHP general-purpose scripting language

web

development

HTML

coding

web server

run


web servers


Operating

System

Platform

PHP
websites


web

server

install

syntax


operating

system

Apache

(web

server)

Perl


Windows


Microsoft
IIS


official current release

PHP 5.3.2 (March 4, 2010)

latest preview release


5.3.3 rc3 (July

15, 2010)


PHP 4 PHP 5

object-oriented programming language


PHP

language


database

open source


PHP


JSP, ROR

ASP.net

..

PHP

PHP
server-side language

code
server

run


server-side language
web page

host
server

information

server

run

browser

web

page

click

click

result

server

Input

server

server-side

client-side language

user

client

run

JavaScript
client web browser

web server

information

Youth Dreams

PHP Guide Book

Moe Myint Shein


browser code

interprets

client-side server-side

form

sign up

text box

data

client side language

valid

submit

server

server

information

web server

save


server side

Fig 1.1 PHP



server

user web page

request

PHP

Apache web server

My SQL Database

PHP

software

localhost

software

package software

software

web server

database

software

windows


WAMP

XAMPP

apache, mysql, php

XAMPP

http://www.apachefriends.org/en/xampp.html

windows version

xampp installer

software

xampp
htdocs

php

folder

save


PHP

PHP,
Apache
MySQL

Install

Part (II)

XAMPP

Web Browser (firefox, IE)


text
editor


PHP editor

Dream weaver CS 4

Notepad

Youth Dreams

PHP Guide Book

Moe Myint Shein

Chapter 2.The Building Blocks of PHP


Basic PHP Syntax
PHP

<?php

?>


PHP block

document

<?

?>

<?php
?>
PHP file

HTML

HTML tag


PHP code


PHP script

browser

Hello World

code

<html>
<body>
<?php
echo "Hello World";
?>
</body>
</html>
code

run

Dreamweaver

PHP

code

Notepad


code

copy paste

save

.. save


C
xampp

htdocs
php



1.php, 2.php

browser

http://localhost/php/1.php, http://localhost/php/2.php

PHP
code

semicolon

semicolon

separator

PHP

text

output

statements

echo
print

echo

Hello World

output

save

.php

.html

PHP code

Comments in PHP
PHP
single line comment
//

/*

*/

Youth Dreams

PHP Guide Book

Moe Myint Shein

<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/

?>
</body>
</html>

PHP Variables
variable

number


strings

arrays

function

result

variable

php script

PHP
variable

$var_name = value;

string variable

number variable

<?php
$txt = "Hello World!";
$number = 10;
?>
PHP
variable

data type

variable

data

type

data type

PHP

Java

Strong
type language

data type


variable

variable name

letter

underscore _

variable name

alpha-numeric characters
underscores (

a-z, A-Z, 0-9,

_ )

Youth Dreams

PHP Guide Book

Moe Myint Shein

variable name

space

variable name
( word )

underscore (_)

($my_string)

capital letter

($myString)

Strings in PHP
String variable

text (character stings)

string

function

operators


String


string

function

variable

Hello

World

String

$txt

string

variable

assign

<?php
$txt = "Hello World";
echo $txt;
?>

output

Hello World

string

function

operators

manipulate

The Concatenation Operator


PHP
string

operator


concatenation operator

(.)

string value

dot (.) operator


string

<?php
$txt1="Hello World";
$txt2="12345";
echo $txt1 . " " . $txt2;
?>

output
Hello World 12345

code

concatenation operator
(.)

string

(empty

space)

Using the strlen() function


strlen() function
string

length


Hello World!

string

length

Youth Dreams

PHP Guide Book

Moe Myint Shein

<?php
echo strlen("Hello World!");
?>

output


12


string

length

looping


function

Using the strpos() function


strpos() function
string

character


string

<?php
echo strpos("Hello World!", "World");
?>

output
6


World

string

position 1

PHP
string

function

PHP Operators

PHP

operator

Arithmetic Operators

Arithmetic Operators

run

<?php
$no1=2;

10

Youth Dreams

10

PHP Guide Book

Moe Myint Shein

$no2=3;
$no3= $no1+$no2;
echo $no3;
?>

code

run
output 5


Division

15

2.5

<?php

$no1=5;
$no2=2;
$no3= $no1/$no2;
echo $no3;
?>
Modulus


5%2

1

.. 10%2

<?php
$no1=5;
$no2=2;
$no3= $no1%$no2;
echo $no3;
?>

Assignment Operators

Assignment Operators

..PHP

x=x+y
x

PHP
assignment operator

x+=y

run

11

Youth Dreams

11

PHP Guide Book

Moe Myint Shein

<?php
$x=5;
$y=2;
$z= $x+=$y;
echo $z;
?>
Output 7

Comparison Operators

Comoparison Operators

==


5 8

5==8

result
false

$x=5;
$y=2;
if ($x==$y)
echo true;
else echo false;
?>

code

run

false

variable x y 3

run
output true

$x=3;
$y=3;
if ($x==$y)
echo "true";
else echo "false";
?>

12

Youth Dreams

12

PHP Guide Book

Moe Myint Shein

Logical Operators

Logical Operators

.. Operator

13

Youth Dreams

13

PHP Guide Book

Moe Myint Shein

Chapter 3.Flow Control Functions in PHP


PHP If Else Statements
PHP
if, elseif
else statements

condition

Conditional Statements

coding

conditional statements

The ifelse statement

code

run
..


code

run

ifelse statement

syntax

if (condition)

code to be executed if condition is true;

else

code to be executed if condition is false;

<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>

</body>
</html>

code
run

Have a nice weekend

Have a nice day

run Have a nice weekend

..

Computer
System Date
Tuesday

run

Have a nice day

:)

14

Youth Dreams

14

PHP Guide Book

Moe Myint Shein

condition

code

run


curly braces

{ }

<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
{
echo "Hello! <br/>";
echo "Have a nice weekend!";
echo " See you on Monday!";
}
?>
</body>
</html>

code

output

Hello!
Have a nice weekend! See you on Monday!

Computer System Date

..
The elseif statement

condition

code
run

elseif statement

syntax

if (condition)

code to be executed if condition is true;

elseif (condition)

code to be executed if condition is true;

else

code to be executed if condition is false;

<html>
<body>

15

Youth Dreams

15

PHP Guide Book

Moe Myint Shein

<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
elseif ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
</body>
</html>

Have a nice weekend!

Have a nice Sunday!

output


Have a nice day!

The Switch Statement

code

run

case


switch case statement

ifelseifelse statement

Syntax

switch (expression )
{

case label1:

code to be executed if expression = label1;


break;

case label2:

code to be executed if expression = label2;


break;

default:

code to be executed

if expression is different

from both label1 and label2;


}

run

<html>
<body>
<?php

16

Youth Dreams

16

PHP Guide Book

Moe Myint Shein

$x=4;
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:

echo "Number 3";


break;
default:
echo "No number between 1 and 3";
}
?>
</body>
</html>

code

run

No

number

between

and

..

$x=2

assign


$x=4

Number 2

output

single expression

variable

evaluate


.. code

case

expression

case

code

execute (run)
execute

case

run
break

case

default statement

execute

PHP Arrays
array

variable

name

variable

variable

array

elements


array

element

(ID)

array

-Numeric array ID key

array

-Associative array- ID key


array

17

Youth Dreams

17

PHP Guide Book

Moe Myint Shein

-Multidimensional array-

array

array

Numeric array
numeric array

$names = array("MgMg","MaMa","KoKo");

ID key


code

manual

$names[0] = "MgMg";
$names[1] = "MaMa";
$names[2] = "KoKo";

PHP coding

<?php>
$names[0] = "MgMg";
$names[1] = "MaMa";
$names[2] = "KoKo";

echo $names[1] . " and " . $names[2] . " are " . $names[0] . "'s neighbours";
?>
output

MaMa and KoKo are MgMg's neighbours

Associative Arrays
associative array
ID key

numerical array

associative
arrays

key

array

assign

array

assign (

$ages = array ("MgMg"=>18,"MaMa"=>20,"KoKo"=>19);




..




array

$ages['MgMg'] = "18";

18

Youth Dreams

18

PHP Guide Book

Moe Myint Shein

$ages['MaMa'] = "20";
$ages['KoKo'] = "19";

code

PHP

<?php>
$ages['MgMg'] = "18";
$ages['MaMa'] = "20";
$ages['KoKo'] = "19";
echo "KoKo is" . $ages['KoKo'] . " years old.";
?>

output
KoKo is19 years old.

Multidimensional Arrays
multidimensional array

array

..


array

element


array

sub array

elelment

array


..

<?php
$families = array
(

"Griffin"=>array
(
"Peter",
"Lois",
"Megan"
),
"Quagmire"=>array
(
"Glenn"
),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
)

);
echo "Is " . $families['Griffin'][2] .
" a part of the Griffin family?";

19

Youth Dreams

19

PHP Guide Book

Moe Myint Shein

?>

php code

$families

variable

array


Griffin, Quagmire,
Brown


Griffin

Peter, Lois, Megan

array

Quagmire

Glenn Brown

Cleveland, Loretta, Junior

run

Output
Is Megan a part of the Griffin family?


Griffin array

Megan


Peter

Lois

PHP Looping
code

run

looping


PHP

looping
statements

while -

code

run


run

dowhile -

code

run

..


run

for -

code

run

foreach array

element

code

run

The while Statement

code

run


run

Syntax
while (condition)
code to be executed;
Example

code
variable i

looping

loop

<html>
<body>
<?php
$i=1;
while ($i<=5)
{
echo "The number is " . $i . "<br/>";
$i++;
}
?>

20

Youth Dreams

20

PHP Guide Book

Moe Myint Shein

</body>
</html>
output

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

variable i

1 assign


..


.. i

{ }
code


The number is 1


output


<br/>


.. i


.. }

while


.. i


.. The number is 2


..

while

.. { }
code

..

The dowhile Statement

code

run

..


run

..


run

Syntax
do
{
code to be executed;
}

while (condition);

Example

<html>

21

Youth Dreams

21

PHP Guide Book

Moe Myint Shein

<body>
<?php
$a=0;
do
{
$a++;
echo "The number is " . $a . "<br/>";
}
while ($a<5);
?>

</body>
</html>

variable a

do {}
code


.. a


echo

The number is 1


..<br/>


..a

do

do { }


..a


looping


..

output
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

The for Statement

code

run

for
statement

syntax
for (init; cond; incr)
{
code to be executed;
}
init

initial value

..

cond
condition

condition

loop


incr

init

increment

Hellow World!

<html>
<body>

22

Youth Dreams

22

PHP Guide Book

Moe Myint Shein

<?php
for ( $i=1; $i<=10; $i++)
{
echo "Hello World!<br />";
}
?>
</body>
</html>
variable i


i 10



..

Hello
World!


.. i


..i 2


.. 10


..


Hello World!


..

program

output

..

10

11

.. Looping


..output

Hello World!

The foreach Statement


foreach statement

array

looping

Syntax (

)
foreach (array as value)
{

code to be executed;
}

<html>
<body>
<?php
$arr=array("one", "two", "three");
foreach ($arr as $value)
{
echo "Value: " . $value. "<br />";
}
?>

</body>
</html>
output

23

Youth Dreams

23

PHP Guide Book

Moe Myint Shein

Value: one
Value: two
Value: three

looping

array element

$value

assign


array
pointer


element

24

Youth Dreams

24

PHP Guide Book

Moe Myint Shein

Chapter 4.Working With Functions & Forms


PHP Functions


PHP

function

..PHP
built-in

functions

700

function

Creating a PHP Function


function
code

..

function

function

function ()

function

function

letter

underscore

function


function
code


..

function

function

Example
<html>
<body>
<?php
function writeMyName()
{
echo "Moe Myint Shein";
}
writeMyName();
?>
</body>
</html>

writeMyName()

function


..

code

screen

.. function

writeMyName();

<html>
<body>

25

Youth Dreams

25

PHP Guide Book

Moe Myint Shein

<?php
function writeMyName()
{
echo "Moe Myint Shein";
}
echo "Hello World! <br />";
echo "My name is ";
writeMyName();
echo ". <br /> That's right, ";
writeMyName();

echo " is my name.";


?>
</body>
</html>

output
Hello World!
My name is Moe Myint Shein.
That's right, Moe Myint Shein is my name.

function

PHP Functions- Adding parameters

writeMyName()

function

string

echo

function

parameters


parameter
variable

writeMyName()

function name

parentheses

()

paramenter

parentheses

Example 1

first name

<html>
<body>
<?php

function writeMyName($fname)
{
echo $fname. "Moe. <br />";
}
echo "My name is ";

26

Youth Dreams

26

PHP Guide Book

Moe Myint Shein

writeMyName("Shwe");
echo "My name is ";
writeMyName("Ngwe");
echo "My name is ";
writeMyName("Sein");
?>
</body>
</html>

output

My name is ShweMoe.
My name is NgweMoe.
My name is SeinMoe

writeMyName ()

function

$fname

parameter

function

code

.. $fname

parameter

Moe

echo

writeMyName()

function

Shwe

parameter

writeMyName(Shwe);

$fname

Shwe


ShweMoe


parameter

<html>
<body>
<?php
function writeMyName($fname, $punctuation)
{
echo $fname. "Moe". $punctuation . "<br />";
}
echo "My name is ";
writeMyName("Shwe", ".");
echo "My name is ";
writeMyName("Ngwe","!");
echo "My name is ";

writeMyName("Sein","...");
?>
</body>
</html>
run

27

Youth Dreams

27

PHP Guide Book

Moe Myint Shein

My name is ShweMoe.
My name is NgweMoe!
My name is SeinMoe...

$punctuation

parameter

. , !,


function

PHP Functions Return Values


function

return

<html>
<body>
<?php
function add($x,$y)
{
$total= $x + $y;
return $total;
}
echo "1+16=" . add(1,16);
?>
</body>
</html>

output - 1+16=17

add () function

$x

$y parameter

parameter

$total

..

$total

return


.. add() function

$total


add(1,16);

function

function

.. 1

16

$total

17


..

return

output
1+16=17

PHP Forms and User Input


user

Form

PHP

$_GET
$_POST

variable


HTML form PHP form

HTML Page

form element

PHP code


<html>
<body>
<form action = "welcome.php" method="post">
Name: <input type="text" name="name"/>
Age:<input type="text" name ="age"/>
<input type="submit"/>
</form>

28

Youth Dreams

28

PHP Guide Book

Moe Myint Shein

</body>
</html>

code

form1.html

save

input field

button


user
form

submit button

form

welcome.php

file



welcome.php

button

object not
found

welcome.php

<html>
<body>

Welcome <?php echo $_POST ["name"]; ?>.<br />


You are <?php echo $_POST ["age"]; ?> years old.
</body>
</html>

welcome.php

form1.html


folder

save


..

form1.html
http://localhost/php/form1.html

run

submit
button

output

Welcome Moe Myint Shein


You are 20 years old.

PHP $_GET
PHP $_GET variable

get method


form

$_GET variable HTTP GET method

variable names

array

GET

method

(browser

address

bar

100 characters

Example
<form action ="welcome1.php" method ="get">
Name:<input type="text" name = "name1"/>
Age: <input type= "text" name = "age1"/>
<input type="submit"/>
</form>

code

form2.php

save

php
html file

C:
xampp
htdocs
php

save

http://localhost/php/form2.php

browser address bar

run

) welcome1.php

file

save


Welcome <?php echo $_GET["name1"]; ?>.<br />

29

Youth Dreams

29

PHP Guide Book

Moe Myint Shein

You are <?php echo $_GET["age1"]; ?> years old!

form2.php
run


text box

submit button

address

bar

http://localhost/php/welcome1.php?name1=Moe+Myint+Shein&age1=20


.. welcome1.php

name1
age1

$GET variable
catch

browser

Welcome moemyintshein.
You are 20 years old!
$_GET variable

variable name

address bar

password

variable

URL

variable values

character
100

THE $ REQUEST Variable


$_REQUEST variable $_GET, $_POST

$_COOKIE


Get method

POST method

data

result

welcome1.php

$_GET
$_REQUEST

Welcome <?php echo $_REQUEST["name1"]; ?>.<br />


You are <?php echo $_REQUEST["age1"]; ?> years old!
PHP $_POST
$_POST variable

HTTP POST method

variable name

values

array

method= post


form

POST method

browser address bar

form3.php

save

Example
<form action="welcome2.php" method="post">
Enter your name: <input type="text" name="name" />
Enter your age: <input type="text" name="age" />
<input type="submit" />
</form>

welcome2.php
code
POST

Welcome <?php echo $_POST["name"]; ?>.<br />


You are <?php echo $_POST["age"]; ?> years old!

30

Youth Dreams

30

PHP Guide Book

Moe Myint Shein

form3.php

run

submit

GET method

address bar

http://localhost/php/welcome2.php


output

GET

method

$_REQUEST Variable
$POST


..

GET method

POST method

31

Youth Dreams

31

PHP Guide Book

Moe Myint Shein

Chapter 5 .PHP Date, Include & File Handling


The PHP Date() Function

function

Syntax
date(format, timestamp)


format

parameter

format


timestamp
optional
default

timestamp


timestamp


1970

GMT 00:00:00


Unix Timestamp

date() function
parameter

format date/time

format

letter

d -


(01-31)

m -


(01-12)

Y digit

/, ., -

character

letter

<?php
echo date("Y/m/d");
echo "<br />";

echo date("Y.m.d");
echo "<br />";
echo date ("Y-m-d");
?>

code

run

output

2009/09/13
2009.09.13
2009-09-13
date()

function

format

parameter


timestamp

PHP Date- Adding a Timestamp


date() function

parameter

timestamp

mktime ()

function


timestamp

mktime() function

specified date

Unix timestamp

return

Syntax

mktime(hour, minute, second, month, day, year, is_dat)

mktime() function
day

argument


32

Youth Dreams

32

PHP Guide Book

Moe Myint Shein

<?php
$tomorrow = mktime(0,0,0,date("m"),date("d")+1, date("Y"));
echo "Tomorrow is ". date("Y/m/d", $tomorrow);
?>

output Tomorrow is 2009/09/14



13

PHP Include File


Server Side Includes

SSI

functions
header
footer
elements

Server Side Includes


include()


require()

function

PHP file


run

file

content


function

include () function

warning


..

script

execute

require () function error

script

execute


function

function header footer


elements

developer

web

page

header

menu file


header
update

include

file

update


site


web page

link

update

menu

file

Example

header.php

header file


header file
page

include() function

<html>
<body>
<?php include("header.php"); ?>
<h1> Welcome to my home page</h1>
<p> Some text</p>
</body>
</html>
Example 2

33

Youth Dreams

33

PHP Guide Book

include

Moe Myint Shein

file

.php

web

page

menu file

menu.php

<html>
<body>
<a href ="http://www.moemyintshein.com/default.php"> Home </a> |
<a href= "http://www.moemyintshein.com/about.php"> About Me</a> |
<a href="http://www.moemyintshein.com/contact.php"> Contact Me</a>
</body>
</html>
default.php , about.php
contact.php

file

menu.php

file

default.php
code

<html>
<body>
<?php include("menu.php");?>
<h1> Welcome to my home page</h1>
<p> Some text</p>
</body>
</html>

menu.php

run
output

Home | About Us | Contact Us


default.php

run

Home | About Us | Contact Us


Welcome to my home page
Some text


default.php
menu.php
directory(folder)

about.php

<html>
<body>
<?php include("menu.php");?>
<h1> Welcome to my about me page.</h1>
<p> Some text</p>
</body>
</html>

34

Youth Dreams

34

PHP Guide Book

Moe Myint Shein

Output

Home | About Us | Contact Us

Welcome to my about me page.


Some text

source

<html>
<body>
<html>

<body>
<a href="http://www.w3schools.com/default.php">Home</a> |
<a href="http://www.w3schools.com/about.php">About Us</a> |
<a href="http://www.w3schools.com/contact.php">Contact Us</a><h1> Welcome to my about me
page.</h1>
<p> Some text</p>
</body>
</html>

contact.php


include

include.php

file

menu

link


site


web page

page

file

menu.php

code

The require() Function


require

()

function

include()

function

error


include() function

warning

script

run


require() function

error message

execute

include() function

error

error message

PHP CODE
<html>
<body>
<?php
include("wrongFile.php");

35

Youth Dreams

35

PHP Guide Book

Moe Myint Shein

echo "Hello World!";


?>
</body>
</html>
ERROR MESSAGE
Warning: include(wrongFile.php) [function.include]: failed to open stream: No such file or directory in
C:\xampp\htdocs\php\10.php
Warning:

include()

on

[function.include]:

(include_path='.;C:\xampp\php\pear\')

line

Failed

in

opening

'wrongFile.php'

C:\xampp\htdocs\php\10.php

for
on

inclusion
line

Hello World!
error message

echo


Hello World
execute

include

warning

execute

require() function

PHP CODE
<html>
<body>
<?php
require("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>
Error Message

Warning: require(wrongFile.php) [function.require]: failed to open stream: No such file or directory in


C:\xampp\htdocs\php\10.php
Fatal

error:

require()

on

[function.require]:

line

Failed

opening

required

'wrongFile.php'

(include_path='.;C:\xampp\php\pear\') in C:\xampp\htdocs\php\10.php on line 5

36

Youth Dreams

36

PHP Guide Book

Moe Myint Shein

echo statement
execute

require

error


execute

include()

require()

recommend



file
missing

script

execute

PHP File Handling


Opening a File
PHP
fopen() function
file


function
parameter

..

parameter

<html>
<body>
<?php

$file=fopen("welcome.txt","r");
?>
</body>
</html>
file

parameter


mode

r
read only




welcome.txt

file

directory

fopen() function

Unable to Open File !

error message

<html>
<body>
<?php

$file=fopen("welcome.txt","r") or exit("Unable to open file!");


?>
</body>
</html>

Closing a File
fcolse() function

..
<?php

37

Youth Dreams

37

PHP Guide Book

Moe Myint Shein

$file = fopen("welcome2.txt","r");
//some code to be executed
fclose($file);
?>
Checking End-of-File
feof() function

(End of File)


function


data length

looping

if (feof($file)) echo End of file;


Reading a File Line by Line
fgets() function

read

read


fopen() function file

false(0)

return

<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br />";
}

fclose($file);
?>

run

welcome.txt

read


echo

browser
welcome.txt

Reading a File Character by Character


fgetc() function

character

read

character

read

<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>

38

Youth Dreams

38

PHP Guide Book

Moe Myint Shein

PHP File Upload

PHP

server

file
upload

user

upload

form

HTML code

upload

<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"/>
<br/>

<input type="submit" name="submit" value="Submit" />


</form>

run

browser

browse

submit

upload

..

form

submit button

upload_file.php

run

upload_file.php

<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";

39

Youth Dreams

39

PHP Guide Book

Moe Myint Shein

echo "Stored in: " . $_FILES["file"]["tmp_name"];


}
?>
PHP $_FILES array

remote server

client computer

parameter

input name


..

index


name, type, size, tmp_name,
error

$_FILES[file][name]- upload

$_FILES[file][type]- upload

$_FILES[file][size]- upload

size (bytes

$_FILES[file][error]-

upload

error code

$_FILES[file][tmp_name]- server

php

upload


security
user

upload

Restrictions on Upload

script

upload


user
gif


jpeg

upload

20

kb

<?php

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";

echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";


echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
}
else
{

40

Youth Dreams

40

PHP Guide Book

Moe Myint Shein

echo "Invalid file";


}
?>

Saving the uploaded File

server

PHP temp folder

upload


php script


upload

store

location

<?php
if ((($_FILES["file"]["type"] == "image/gif")

|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";

echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";


if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}

else
{

41

Youth Dreams

41

PHP Guide Book

Moe Myint Shein

echo "Invalid file";


}
?>
upload_file.php


code

upload.php

run

php
directory (C:\xampp\htdocs\php)

upload

folder

..

upload

upload

folder

file

local


web hosting

PHP Cookies
cookie

user

identity


cookie
user


browser

web page

request

cookie

PHP


cookie

How to Create a Cookie?


cookie

setcookie() function


setcookie() function
<html> tag

setcookie (name,value,expire,path,domain);

cookie

set

syntax

Example

user

cookie


Alex

Porter

expire

<?php
setcookie("user", "Alex Porter", time()+3600);
?>

<html>
....
cookie
expire time

<?php
$expire=to,e()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>
<html>
.....

expire time


(60 sec * 60 min * 24 hours * 30
days).

42

Youth Dreams

42

PHP Guide Book

Moe Myint Shein

Cookie

Retrieve

<?php
//Print a cookie
echo $_COOKIE["user"];
// A way to view all cookies
print_r($_COOKIE);
?>

user

cookie

isset()

function

cookie

<html>
<body>
<?php
if (isset($_COOKIE["user"]))
echo "Welcome" . $_COOKIE["user"] . "!<br/>";
else
echo "Welcome guest!<br />";
?>
</body>
</html>

Cookie

cookie

expiration date

<?php
//set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
Browser

Cookie

support

form

Submit button

user

welcome.php

user input

<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"/>

43

Youth Dreams

43

PHP Guide Book

Moe Myint Shein

Age : <input type="text" name ="age"/>


<input type="submit"/>
</form>
</body>
</html>

code

form1.php

save

welcome.php

retrieve

<html>

<body>
Welcome <?php echo $_POST["name"]; ?>. <br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>

forum1.php
Browser
run

text box

submit

moemyintshein

20

submit

Welcome moemyintshein.
You are 20 years old.

PHP Sessions

PHP session variable

user session


user

application


application


..

.
session

computer


web server

..

HTTP
state

maintain


PHP session

remember

user

server

session

information


user

website

database

data


session

unique id( UID)

visitor

UID

variable


UID

cookie

URL

propagated

Starting a PHP Session

44

Youth Dreams

44

PHP Guide Book

Moe Myint Shein

PHP session

user information

session

session_start() function

<html> tag

<?php session_start(); ?>


<html>
<body>
</body>
</html>

server

user session
register


user Information

user session

UID

assign

Storing a Session Variable


session variable



PHP $_SESSION variable

<?php
session_start();
//store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data

echo "Pageviews=" . $_SESSION['views'];


?>
</body>
</html>
output

Pageviews=1

page view counter


isset() function


views

variable


..

counter

views variable

<?php

session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;

45

Youth Dreams

45

PHP Guide Book

Moe Myint Shein

echo "Views=". $_SESSION['views'];


?>

run

. relode

views

Destroying a Session
session

data


unset()

function

sessopm_destroy()

function


unset() function

session variable
free

<?php

unset($_SESSION['views']);
?>
session_destroy()function

session


<?php
session_destroy();
?>
PHP Mail Function
PHP script

PHP
mail() function

Syntax
mail(to,subject,message,headers,parameters)

parameter

to, subject, message

headers
parameters
Optional

PHP Simple E-Mail

46

Youth Dreams

46

PHP Guide Book

Moe Myint Shein

PHP


text

$to, $subject, $message, $from, $headers

variable


mail() function

<?php
$to= "mail@moemyintshein.com";
$subject="Test mail";
$message="Hello! This is a simple email message.";
$from= "gtalk@moemyintshein";
$headers="From: $from";

mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>
PHP Mail Form
PHP

website

feedback-form


form

<html>
<body>
<?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
{
//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail( "someone@example.com", "Subject: $subject",
$message, "From: $email" );
echo "Thank you for using our mail form";
}
else

//if "email" is not filled out, display the form


{
echo "<form method='post' action='mailform.php'>
Email: <input name='email' type='text' /><br />
Subject: <input name='subject' type='text' /><br />
Message:<br />

47

Youth Dreams

47

PHP Guide Book

Moe Myint Shein

<textarea name='message' rows='15' cols='40'>


</textarea><br />
<input type='submit' />
</form>";
}
?>
</body>
</html>

code

save

mailform.php

save


email

input

field

HTML form


form


submit buttion

page

reload


input field

SMTP

smtp_post

php.ini file


..

..

..

security

PHP Secure E-mails


PHP E-mail Injections

48

Youth Dreams

48

PHP Guide Book

Moe Myint Shein

code


unauthorized user
input form
mail
header

data

user form
input fileld

someone@example.com%0ACc:person2@example.com
%0ABcc:person3@example.com,person3@example.com,
anotherperson4@example.com,person5@example.com
%0ABTo:person6@example.com

code form
email field

input

validate

<html>
<body>
<?php
function spamcheck($field)
{
//filter_var() sanitizes the e-mail
//address using FILTER_SANITIZE_EMAIL
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
//filter_var() validates the e-mail
//address using FILTER_VALIDATE_EMAIL

if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_REQUEST['email']))
{//if "email" is filled out, proceed
//check if the email address is invalid
$mailcheck = spamcheck($_REQUEST['email']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
}

49

Youth Dreams

49

PHP Guide Book

Moe Myint Shein

else
{//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail("someone@example.com", "Subject: $subject",
$message, "From: $email" );
echo "Thank you for using our mail form";
}
}

else
{//if "email" is not filled out, display the form
echo "<form method='post' action='mailform.php'>
Email: <input name='email' type='text' /><br />
Subject: <input name='subject' type='text' /><br />
Message:<br />
<textarea name='message' rows='15' cols='40'>
</textarea><br />
<input type='submit' />
</form>";
}
?>
</body>
</html>

code

PHP Filter


input

The FILTER_SANITIZE_EMAIL filter

string

illegal email character

The

FILTER_VALIDATE_EMAIL


email

format


PHP Filter

filter

PHP Error Handling


PHP
default error handling

error message
error


browser

web application

error handling

code
error checking code


security risk

PHP
error

50

Simple die() statements

Youth Dreams

50

PHP Guide Book

Moe Myint Shein

Custom errors and error triggers

Error reporting

Basic Error Handling: Using the die() function


text file

code

..

error

Warning: fopen(welcome.txt) [function.fopen]: failed to open stream: No such file or directory in


C:\xampp\htdocs\php\20.php on line 2

error message

user

..

code

access

<?php
if(!file_exists("welcome.txt"))
{
die("File not found");
}
else
{
#file=fopen("welcome.txt"."r");
}

?>

welcome.txt

File not found

error message


code

..error

code

run

error handling

..
error handling

php function

Creating a Custom Error Handler


error

function

function

parameters

( error level
error message)

parameter


(optional: file, line number, error context)
Syntax
error_function (error_level, error_message, error_file, error_line, error_context)

51

Youth Dreams

51

PHP Guide Book

Moe Myint Shein

Error Report Levels


user

error handler

error

error report levels

..

error

function

function customError($errno, $errstr)


{
echo "<b>Error:</b> [$errno] $errstr<br />";
echo "Ending Script";
die();
}

code

error handling function

run

error level

error message

output

script

error handling function

trigger

( run
)

Set Error Handler


PHP
default error handler
built in error handler

function

default error
handler

script



error

error handler

52

Youth Dreams

52

PHP Guide Book

Moe Myint Shein

error

error

error handler

set_error_handler(customError);
error

function

set_error_handler() function

parameter

parameter

error

level

variable
Output

error handler

<?php
//error handler function
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr";
}
//set error handler
set_error_handler("customError");
//trigger error
echo($test);
?>

run

- Error: [8] Undefined variable: test

output

Trigger an Error
user data

input

script

illegal input

errors

trigger


PHP

trigger_error() function


test
varuable 1

error

<?php
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below");
}
?>

run

output

Notice: Value must be 1 or below in C:\xampp\htdocs\php\30.php on line 5

53

Youth Dreams

53

PHP Guide Book

Moe Myint Shein

Chapter 6. PHP & AJAX


PHP and AJAX
AJAX INTRODUCTION
AJAX= Asynchronous JavaScript And XML
AJAX web browser

web server

data

JavaScript

AJAX

user

web

page

relode

web server

data exchange

web page


responsive


AJAX
standards

-JavaScript
-XML
-HTML
-CSS
PHP

AJAX

JavaScript, XML, HTML,CSS



PHP

..


..

AJAX

major browser

support

AJAX application
browser

platform

Cross Platform, Cross Browser Technology

AJAX Uses XML And HTTP Requests

web application

html form

input

web server

submit

web server data

process

user

web page

return



user input

web page

server

user friendly

AJAX

web application

web page

relode

data

server

HTTP request


server data


JavaScript

web page

modify

PHP and AJAX


AJAX


server

..

AJAX

browser

run


browser
web server

HTTP requests (asynchronous data transfer)

web page

server

web page

AJAX web server software

web

browser

technology


tutorial

PHP

server

run

54

Youth Dreams

54

PHP Guide Book

Moe Myint Shein

AJAX XMLHttpReuest
XMLHttpRequest object

AJAX


July 2000 Internet Explorer

2005
AJAX
Web 2.0

browser

XMLHttpRequest object



Internet Explorer ActiveXObject

browser
build in
JavaScript object

XMLHttpRequest

code

var XMLHttp=null
if (window.XMLHttpRequest)
{
XMLHttp=new XMLHttpRequest()
}

else if (window.ActiveXObject)
{
XMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}

XMLHttpRequest object

XMLHttp variable

null

window.XMLHttpRequest

object available


Firefox, Opera, Safari

version

available

available

XMLHttp=new

XMLHttpRequest()

object


available

window.ActiveXObject available


Internet Explorer 5.5

available


available

XMLHttp=new ActiveXObject()

object

XMLHttpRequest object





Microsoft.XMLHTTP Xsxml2.XMLHTTP

Microsoft

latest version

load

IE 6

available

function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{

// Internet Explorer
try
{

55

Youth Dreams

55

PHP Guide Book

Moe Myint Shein

xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}

XMLHttpRequest object

XMLHttp

variable

web standarads (Mozila, Opera

Safari)XMLHttp= new XMLHttpRequest() object



Microsoft

IE


XMLHttp=new

ActiveXObject(Msxml2.XMLHTTP object

error

(IE 5.5) XMLHttp=new ActiveXObject( Microsoft.XMLHTTP)

AJAX Suggest

AJAX
user web form

data

web page

web server

communticate

box

character

suggestion

page

HTML page

JavaScript page

PHP page

The HTML Form


HTML page

form

HTML code
JavaScript

link

html file

ajaxtesting.html

<html>
<head>
<script src="clienthint.js"></script>
</head>
<body>

56

Youth Dreams

56

PHP Guide Book

Moe Myint Shein

<form>
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>

txt1

Input filed

HTML form

1.

user input field

keyboard
key

release

event

2.

evernt

showHint()

function

execute

3.

form

txtHint

<span>

showHint()

return data


JavaScript code

clienthint.js

HTML document

var xmlHttp;
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}

var url="gethint.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);

57

Youth Dreams

57

PHP Guide Book

Moe Myint Shein

}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{

xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}// JavaScript Document

showHint()function inpurt field

character



input filed

input

str.length>0

execute

1.

server

url filename

gethint.php

2.

input

filed


content

(character)


parameter

(q)

3.

58

server cached file

random number

Youth Dreams

58

PHP Guide Book

Moe Myint Shein

4.

GetXmlHttpObject function


XMLHTTP object

object

StateChanged

function

execute

5.

url

XMLHTTP object

6.

server

HTTP request

input filed

function txtHint

placeholder (suggestion

content (
)

The stateChanged() Function


XMLHTTP object
state

function

execute(

state 4

complete

txtHint
content

response

text

The GetXmlHttpObject() Function


AJAX applications
XML support

browser
run


GetXMLHttpObjet()

XMLHTTP object

PHP page


JavaScript code

server page
gethint.php

Php file

gethint.php

code

array

client

return

<?php
// Fill up array with names
$a[]="Anna";

$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";

$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";

59

Youth Dreams

59

PHP Guide Book

Moe Myint Shein

$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";

//get the q parameter from URL


$q=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{

$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
//Set output to "no suggestion" if no hint were found
//or to the correct values
if ($hint == "")
{

$response="no suggestion";
}
else
{
$response=$hint;

60

Youth Dreams

60

PHP Guide Book

Moe Myint Shein

}
//output the response
echo $response;
?>
JavaScript

(strlen($q)>0)

text

1.

JavaScript

character

match

2.

response string

3.

match

no suggestion

response

5.

response

txtHint placeholder

4.

response

clienthint.js , gethint.php ajaxtesting.html

folder directory

save

..

ajaxtesting.html

browser
run
PHP

AJAX

web application

:D

PHP AND AJAX XML EXAMPLE


AJAX
XML file


web page

AJAX

XML file

(fetch)


Select a CD:

drop down box

..

CD info


HTML form

XML file
JavaScript
PHP page

THE HTML FORM

HTML form


JavaScript

HTML code

ajaxxml.html

save

<html>
<head>
<script src="selectcd.js"></script>
</head>
<body>
<form>
Select a CD:
<select name="cds" onchange="showCD(this.value)">
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bee Gees">Bee Gees</option>

<option value="Cat Stevens">Cat Stevens</option>


</select>
</form>

61

Youth Dreams

61

PHP Guide Book

Moe Myint Shein

<p>
<div id="txtHint"><b>CD info will be listed here.</b></div>
</p>
</body>
</html>

HTML form


cds

drop down box

txtHint

div


div
web server

placeholder


user data

showCD

function

execute(run)


onchange event

function
run

user drop down box


showCD

function

XML file

code

cd_catalog.xml
save

ajaxxml.html

file

folder

<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>

<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>

<CD>
<TITLE>Greatest Hits</TITLE>
<ARTIST>Dolly Parton</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>RCA</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1982</YEAR>
</CD>

<CD>
<TITLE>Still got the blues</TITLE>
<ARTIST>Gary Moore</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Virgin records</COMPANY>
<PRICE>10.20</PRICE>

62

Youth Dreams

62

PHP Guide Book

Moe Myint Shein

<YEAR>1990</YEAR>
</CD>

<CD>
<TITLE>Eros</TITLE>
<ARTIST>Eros Ramazzotti</ARTIST>
<COUNTRY>EU</COUNTRY>
<COMPANY>BMG</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1997</YEAR>
</CD>

<CD>
<TITLE>One night only</TITLE>
<ARTIST>Bee Gees</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Polydor</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1998</YEAR>
</CD>

<CD>
<TITLE>Sylvias Mother</TITLE>
<ARTIST>Dr.Hook</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS</COMPANY>
<PRICE>8.10</PRICE>
<YEAR>1973</YEAR>
</CD>

<CD>
<TITLE>Maggie May</TITLE>
<ARTIST>Rod Stewart</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Pickwick</COMPANY>
<PRICE>8.50</PRICE>
<YEAR>1990</YEAR>
</CD>

<CD>
<TITLE>Romanza</TITLE>
<ARTIST>Andrea Bocelli</ARTIST>
<COUNTRY>EU</COUNTRY>
<COMPANY>Polydor</COMPANY>
<PRICE>10.80</PRICE>
<YEAR>1996</YEAR>
</CD>

<CD>
<TITLE>When a man loves a woman</TITLE>
<ARTIST>Percy Sledge</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Atlantic</COMPANY>
<PRICE>8.70</PRICE>
<YEAR>1987</YEAR>
</CD>

<CD>
<TITLE>Black angel</TITLE>
<ARTIST>Savage Rose</ARTIST>

63

Youth Dreams

63

PHP Guide Book

Moe Myint Shein

<COUNTRY>EU</COUNTRY>
<COMPANY>Mega</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1995</YEAR>
</CD>

<CD>
<TITLE>1999 Grammy Nominees</TITLE>
<ARTIST>Many</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Grammy</COMPANY>
<PRICE>10.20</PRICE>
<YEAR>1999</YEAR>
</CD>

<CD>
<TITLE>For the good times</TITLE>
<ARTIST>Kenny Rogers</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Mucik Master</COMPANY>
<PRICE>8.70</PRICE>
<YEAR>1995</YEAR>
</CD>

<CD>
<TITLE>Big Willie style</TITLE>
<ARTIST>Will Smith</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1997</YEAR>
</CD>

<CD>
<TITLE>Tupelo Honey</TITLE>
<ARTIST>Van Morrison</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Polydor</COMPANY>
<PRICE>8.20</PRICE>
<YEAR>1971</YEAR>
</CD>

<CD>
<TITLE>Soulsville</TITLE>
<ARTIST>Jorn Hoel</ARTIST>
<COUNTRY>Norway</COUNTRY>
<COMPANY>WEA</COMPANY>
<PRICE>7.90</PRICE>
<YEAR>1996</YEAR>
</CD>

<CD>
<TITLE>The very best of</TITLE>
<ARTIST>Cat Stevens</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Island</COMPANY>
<PRICE>8.90</PRICE>
<YEAR>1990</YEAR>
</CD>

64

Youth Dreams

64

PHP Guide Book

Moe Myint Shein

<CD>
<TITLE>Stop</TITLE>
<ARTIST>Sam Brown</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>A and M</COMPANY>
<PRICE>8.90</PRICE>
<YEAR>1988</YEAR>
</CD>

<CD>
<TITLE>Bridge of Spies</TITLE>
<ARTIST>T'Pau</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Siren</COMPANY>
<PRICE>7.90</PRICE>
<YEAR>1987</YEAR>
</CD>

<CD>
<TITLE>Private Dancer</TITLE>
<ARTIST>Tina Turner</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>Capitol</COMPANY>
<PRICE>8.90</PRICE>
<YEAR>1983</YEAR>
</CD>

<CD>
<TITLE>Midt om natten</TITLE>
<ARTIST>Kim Larsen</ARTIST>
<COUNTRY>EU</COUNTRY>
<COMPANY>Medley</COMPANY>
<PRICE>7.80</PRICE>
<YEAR>1983</YEAR>
</CD>

<CD>
<TITLE>Pavarotti Gala Concert</TITLE>
<ARTIST>Luciano Pavarotti</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>DECCA</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1991</YEAR>
</CD>

<CD>
<TITLE>The dock of the bay</TITLE>
<ARTIST>Otis Redding</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Atlantic</COMPANY>
<PRICE>7.90</PRICE>
<YEAR>1987</YEAR>
</CD>

<CD>
<TITLE>Picture book</TITLE>
<ARTIST>Simply Red</ARTIST>
<COUNTRY>EU</COUNTRY>
<COMPANY>Elektra</COMPANY>
<PRICE>7.20</PRICE>

65

Youth Dreams

65

PHP Guide Book

Moe Myint Shein

<YEAR>1985</YEAR>
</CD>

<CD>
<TITLE>Red</TITLE>
<ARTIST>The Communards</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>London</COMPANY>
<PRICE>7.80</PRICE>
<YEAR>1987</YEAR>
</CD>

<CD>
<TITLE>Unchain my heart</TITLE>
<ARTIST>Joe Cocker</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>EMI</COMPANY>
<PRICE>8.20</PRICE>
<YEAR>1987</YEAR>
</CD>
</CATALOG>

code
selectcd.js

JavaScript code

var xmlHttp
function showCD(str)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="getcd.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{

66

Youth Dreams

66

PHP Guide Book

Moe Myint Shein

// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
stateChanged()

GetXmlHttpObject

showCD()

function

drop

down

box

item

showHint()

JavaScript

server page getcd.php

XML

document

cd_catalog.xml

load

XML

DOM

PHP

XML file
query run

HTML

result

return

<?php
$q=$_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->load("cd_catalog.xml");
$x=$xmlDoc->getElementsByTagName('ARTIST');
for ($i=0; $i<=$x->length-1; $i++)
{
//Process only element nodes
if ($x->item($i)->nodeType==1)
{
if ($x->item($i)->childNodes->item(0)->nodeValue == $q)
{
$y=($x->item($i)->parentNode);
}
}
}
$cd=($y->childNodes);
for ($i=0;$i<$cd->length;$i++)
{
//Process only element nodes
if ($cd->item($i)->nodeType==1)
{
echo($cd->item($i)->nodeName);
echo(": ");
echo($cd->item($i)->childNodes->item(0)->nodeValue);
echo("<br />");
}
}
?>

67

Youth Dreams

67

PHP Guide Book

Moe Myint Shein

JavaScript PHP page

query

1.

PHP cd_catalog.xml file


XML DOM object

2.

artist elements (nodetypes=1)


JavaScript

match

loop

3.

artist

CD

4.

album

Output

txtHint placeholder

PHP and AJAX RSS Reader


RSS Reader

RSS Feeds


RSS


up to date

AJAX RSS Reader



webpage
refresh

RSS
content

load

RSS
reader

HTML page

JavaScript

PHP

The HTML Form

getrss.js

JavaScript

<html>
<head>
<script type="text/javascript" src="getrss.js"></script>
</head>
<body>
<form>
Select an RSS-Feed:
<select onchange="showRSS(this.value)">
<option value="Google">Google News</option>
<option value="MSNBC">MSNBC News</option>
</select>
</form>
<p><div id="rssOutput">
<b>RSS Feed will be listed here.</b></div></p>
</body>
</html>

HTML page
drop-down box

HTML form

68

Youth Dreams

68

PHP Guide Book

Moe Myint Shein

user drop down box


option

event

showRSS()

function

rssOutput

<div>
showRSS() function return


data

placeholder

The JavaScript

code
getrss.js

JavaScript code

var xmlHttp
function showRSS(str)
{
xmlHttp=GetXmlHttp Object()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="getrss.php"
url=url+"?q="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("rssOutput")
.innerHTML=xmlHttp.responseText
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
JavaScript code

getrss.php

PHP file

..

server page

69

Youth Dreams

69

PHP Guide Book

Moe Myint Shein

<?php
//get the q parameter from URL
$q=$_GET["q"];
//find out which feed was selected
if($q=="Google")
{
$xml=("http://news.google.com/news?ned=us&topic=h &output=rss");
}
elseif($q=="MSNBC")
{
$xml=("http://rss.msnbc.msn.com/id/3032091/device/rss/rss.xml");
}
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);
//get elements from "<channel>"
$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
//output elements from "<channel>"
echo("<p><a href='" . $channel_link
. "'>" . $channel_title . "</a>");
echo("<br />");
echo($channel_desc . "</p>");
//get and output "<item>" elements
$x=$xmlDoc->getElementsByTagName('item');
for ($i=0; $i<=2; $i++)
{
$item_title=$x->item($i)->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$item_link=$x->item($i)->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$item_desc=$x->item($i)->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
echo ("<p><a href='" . $item_link
. "'>" . $item_title . "</a>");
echo ("<br />");
echo ($item_desc . "</p>");
}
?>
JavaScript option


RSS feed

PHP

XML DOM object

RSS feed

RSS channel

element

output

RSS items

loop

output

rssreader.html

run

70

Youth Dreams

70

PHP Guide Book

Moe Myint Shein

PHP AND AJAX POLL



Ajax example
web page relode

result

Poll

HTML form

JavaScript

PHP page

Yes, No result

text file

The HTML Form

HTML

HTML form


JavaScript

link

<html>
<head>
<script src="poll.js"></script>
</head>
<body>
<div id="poll">
<h2>Do you like PHP and AJAX so far?</h2>
<form>
Yes:
<input type="radio" name="vote"
value="0" onclick="getVote(this.value)">
<br />No:
<input type="radio" name="vote"
value="1" onclick="getVote(this.value)">
</form>
</div>
</body>
</html>

ajaxpoll.html

save


<div> tag

Yes

No

radio button

form

user yes

no

event

event

getVote()

function

execute


getVote() function


data

form
replace

The Text File


text file

poll_result.txt


save

poll
.. data

0||0

Yes votes

||


No votes

..

Yes
vote

01

The JavaScript
JavaScript code

poll.js

71

Youth Dreams

71

PHP Guide Book

Moe Myint Shein

var xmlHttp
function getVote(int)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="poll_vote.php"
url=url+"?vote="+int
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("poll").
innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var objXMLHttp=null
if (window.XMLHttpRequest)
{
objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}
Yes

No

HTML form

select

getVote() function

JavaScript

poll_vote.php

<?php
$vote = $_REQUEST['vote'];
//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);
//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];
if ($vote == 0)
{

72

Youth Dreams

72

PHP Guide Book

Moe Myint Shein

$yes = $yes + 1;
}
if ($vote == 1)
{
$no = $no + 1;
}
//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>
<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>
Yes (0) , No (1)

JavaScript

poll_result.txt file
content

contact

variable

variable

JavaScript

result

poll_result.txt

update

poll result
graphical representation

ajaxpoll.html

run

Do you like PHP & AJAX so far?

poll

Yes, No button


ajaxpoll.html

Do you like PHP &


AJAX

so

far

Yes

No

Yes

run

:P

73

Youth Dreams

73

PHP Guide Book

Moe Myint Shein

Chapter 7. PHP MyAdmin Basic

PHP, MySQL

Apache

Package

XAMPP

root

username

password


..
Database


username

password


..MySQL

User


..
Creating a New User
Database

http://localhost/phpmyadmin/

. PHP My Admin

tool

Database


.. User

SQL Statement


PHP

Admin

Create

New

User


..
http://localhost/phpmyadmin/

Web Browser

Privileges

..

74

Youth Dreams

74

PHP Guide Book

Moe Myint Shein

Privileges

Create a new User



..

user

75

Youth Dreams

75

PHP Guide Book

Moe Myint Shein

Username
moemyintshein host
localhost
password
moemyintshein

Global privileges
Check All

..

Go

user

..


execute

SQL

Statement

.. you have added a new user

Message


..


user

..

moemyintshein

localhost

SQL

statement


..

Server

user

SQL statement

username

moemyintshein1 password

moemyint12345

76

Youth Dreams

76

PHP Guide Book

Moe Myint Shein

PHP Admin main page


button

SQL

SQL query
execute

pop up page




..

GRANT ALL ON *.* TO moemyintshein1@localhost IDENTIFIED BY "moemyint12345";

Go

localhost

Server
moemyint12345

password

moemyintshein1

user

privileges

root

user


..

user

PHP MyAdmin

Table

Database

Home

Databases

menu

Create New Database


Database

mydomain


Collation

utf8_general_ci

mydomain

database

people

table

field

Go

77

Youth Dreams

77

PHP Guide Book

Moe Myint Shein

Go

mydomain

database

people

table

table

save

PHP MyAdmin

78

Youth Dreams

78

PHP Guide Book

Moe Myint Shein

save

length value input character


Type

efficient


PHP MyAdmin

function

Drop

table

Primary Key

id fileld
auto_increment


record

Input

Default

save

screen

79

Youth Dreams

79

PHP Guide Book

Moe Myint Shein

table

table

SQL command

PHP

Database

Table

Data

Insert

tab

80

Youth Dreams

80

PHP Guide Book

Moe Myint Shein

Insert


field

setting

save

SQL code

window

id column auto increment

Browse Tab

edit

Delete

back up

Database

database
mydomain

Tab

Export

81

Youth Dreams

81

PHP Guide Book

Moe Myint Shein


people

export

backup

table

save

as

file

checked

zipped

GO

mydomain.sql

Zip

backup




Database

table

fileds

records


record


edit

back up

82

Youth Dreams

82

PHP Guide Book

Moe Myint Shein

Chapter 8.PHP and Database

PHP, My SQL Database


Apache Web Server

PHP

XAMPP


Install

..

PHP


XAMPP

PHP Myadmin

tool

PHP Database
PHP MySQL Introduction
What is MySQL?
MySQL

open source database system

MySQL
database

MySQL

tables

database objects


table

column rows

Database

..
Database Tables

database

table

table

(Customers,
Orders). Table

rows

records


Persons

table

table

records (rows)

column(LastName, firstName,
Address

City)

Queries
query


query

SELECT LastName FROM Persons


query
Persons table
LastName

column

Create a Connection to a MySQL Database

83

Youth Dreams

83

PHP Guide Book

Moe Myint Shein

database

data access

database
connection

PHP

mysql_connect() function

Syntax
mysql_connect(servername,username,password);


code

connection

($con)

variable

.. script


connection fail

die

<?php
$con=mysql_connect("localhost","user","password");
if (!$con)
{
die('Could not connect:' > mysql_error());
}
//some code
?>
PHP Script

connection


mysql_done()
fucntoin

<?php

$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_close($con);
?>
PHP MySQL Create Database and Tables
Create a Database
MySQL
database

CREATE DATABASE statement


Syntax

CREATE DATABASE database_name

PHP tutorial


database


..

SQL

SQL

84

Youth Dreams

84

PHP Guide Book

Moe Myint Shein

execute

mysql_query() function


function
MySQL connection

query

command


my_db

database

<?php
$con = mysql_connect("localhost","user","moemyintshein");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_close($con);
?>

Table

CREATE TABLE statement

MySQL
table

syntax
CREATE TABLE table_name
(
colomn_name1 data_type,
colomn_name2 data_type,
column_name3 data_type,


SQL

SQL Tutorial

PHP

mysql_query() function

CREATE TABLE statement

execute

Persons

table

FirstName, LastName
Age

Colomn

<?php
$con = mysql_connect("localhost","root","moemyintshein");
if (!$con)

85

Youth Dreams

85

PHP Guide Book

Moe Myint Shein

{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE my_db1",$con))
{
echo "Database created";
}
else
{

echo "Error creating database: " . mysql_error();


}
// Create table
mysql_select_db("my_db1", $con);
$sql = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>

- table

database

mysql_select_db()

function


database


varchar type


database field

filed
maximum length varchar(15)

data type

column

data

Primary Keys and Auto Increment Fields


table

rows

primary key


primar y key

table

primary

key

null

database engine

record

personID

field

primary key filed


primary key
filed

ID number

AUTO_INCREMENT setting


AUTO_INCREMENT

record (column)


primary

86

Youth Dreams

86

PHP Guide Book

Moe Myint Shein

key

field


primary key filed
null

field

NOT NULL

setting

$sql = "CREATE TABLE Persons


(
personID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(personID),
FirstName varchar(15),
LastName varchar(15),
Age int
)";
mysql_query($sql,$con);

PHP MySQL Insert Into


INSERT INTO statement

table

column(record)

Syntax
INSERT INTO statement


data

column

INSERT INTO table_name


VALUES (value1, value2, value3,...)


column name

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)
PHP

statement

execute

mysql_query()

function

function
MySQL connection

query


command

Persons

table

Firstname, Lastname

Age

Column


table

Persons

table

record

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)

87

Youth Dreams

87

PHP Guide Book

Moe Myint Shein

{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', '35')");
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire', '33')");
mysql_close($con);
?>
Insert Data From a Form Into a Database

Persons table

record

HTML form

HTML form

<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
user

HTML form

Submit button

form

data

insert.php

insert.php

database


PHP $_POST variables

form


mysql_query() function

INSERT INTO
statement

Persons table

record

insert.php

code

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>

88

Youth Dreams

88

PHP Guide Book

Moe Myint Shein

PHP MySQL Select


Select Data From a Database Table
SELECT statement

database

data

select

Syntax
SELECT column_name(s)
FROM table_name

PHP

mysql_query() function

Persons table

data

character

table

data

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
mysql_close($con);
?>

mysql_query() return


data

$result

variable

array

recrodset

row

return

mysql_fetch_array () function


mysql_fetch_array()

recordset


row

return


while loop recordset
record

Looping


row

Screen

Print

PHP

$row

variable

($row['FirstName'] and $row['LastName'])

code
Output

89

Youth Dreams

89

PHP Guide Book

Moe Myint Shein

Peter Griffin
Glenn Quagmire
Display the Result in an HTML Table

data


HTML tab;e

data

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>

code

output

PHP MySQL The Where Clause


WHERE clause

record

90

Youth Dreams

90

PHP Guide Book

Moe Myint Shein

Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator value

Persons table
FirstName Peter

row

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons
WHERE FirstName='Peter'");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
?>
output

Peter Griffin

PHP MySQL Order By Keyword


ORDER BY keyword

recordset

data

ORDER BY keyword
default

ascending order

record

descending order

record

DESC keyword

Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC

91

Youth Dreams

91

PHP Guide Book

Moe Myint Shein

Persons table

data

Age
column

result

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons ORDER BY age");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br />";
}
mysql_close($con);
?>

code
output
Glenn Quagmire 33
Peter Griffin 35

Order by Two Columns


column


order

by

column

Ordering

column

column

SELECT column_name(s)
FROM table_name
ORDER BY column1, column2
PHP MySQL Update
UPDATE statement

table

record


Update

Syntax
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

92

Youth Dreams

92

PHP Guide Book

Moe Myint Shein

WHERE clause


UPDATE syntax

WHERE clause


record


WHERE

records

Update

Persons

Table

..


Persons table

data

update

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("UPDATE Persons SET Age = '36'
WHERE FirstName = 'Peter' AND LastName = 'Griffin'");
mysql_close($con);
?>
Update

Persons table

PHP MySQL Delete


DELETE statement
database table
records


FROM


DELETE

Syntax
DELETE FROM table_name
WHERE some_column = some_value

WHERE clause


WHERE clause
record


WHERE

records

Delete

93

Youth Dreams

93

PHP Guide Book

Moe Myint Shein

Persons table


code

LasteName Griffin

Persons table
record

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("DELETE FROM Persons WHERE LastName='Griffin'");
mysql_close($con);
?>
Delete

PHP Database ODBC


ODBC

Microsoft Access Database

Data Source


Application
Programming Interface (API)

Create an ODBC Connection


ODBC connection

ODBC connection


database


MS Access Database

ODBC Connection

1. Open the Administrative Tools icon in your Control Panel.


2. Double-click on the Data Sources (ODBC) icon inside.
3. Choose the System DSN tab.

94

Youth Dreams

94

PHP Guide Book

Moe Myint Shein

4.
5.
6.
7.
8.

Click on Add in the System DSN tab.


Select the Microsoft Access Driver. Click Finish.
In the next screen, click Select to locate the database.
Give the database a Data Source Name (DSN).
Click OK.

configuration
website


Internet
Information Server

IIS

run

instruction

remote server

website

server
Physical access

web host

DNS

set up

Connecting to an ODBC
odbc_connect() function

ODBC data source

function
parameter


data source

username
Password

Optical cursor type

SQL statement

execute

odbc_exec() function



northwind

DNS

connection

username
password

northwind


SQL

execute

$conn=odbc_connect('northwind','','');
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);

Retrieving Records
odbc_fetch_row()

result-set record

return


function rows

return

true

false

function
ODBC result identifier

Optical row number

parameter

odbc_fetch_row($rs)
Retrieving Fields from a Record
odbc_result() function record

fields

function ODBC result


identifier

field number

name

parameter


.

code line

record

field

return

$compname=odbc_result($rs,1);

95

Youth Dreams

95

PHP Guide Book

Moe Myint Shein


code line
CompanyName

field

return

$compname=odbc_result($rs,"CompanyName");
Closing an ODBC Connection
odbc_close() function

ODBC connection

odbc_close($conn);
ODBC

database connection

result set

HTML
table

data

<html>
<body>
<?php
$conn=odbc_connect('northwind','','');
if (!$conn)
{exit("Connection Failed: " . $conn);}
$sql="SELECT * FROM customers";
$rs=odbc_exec($conn,$sql);
if (!$rs)
{exit("Error in SQL");}
echo "<table><tr>";
echo "<th>Companyname</th>";
echo "<th>Contactname</th></tr>";
while (odbc_fetch_row($rs))
{
$compname=odbc_result($rs,"CompanyName");
$conname=odbc_result($rs,"ContactName");
echo "<tr><td>$compname</td>";
echo "<td>$conname</td></tr>";
}
odbc_close($conn);
echo "</table>";
?>
</body>
</html

96

Youth Dreams

96

PHP Guide Book

Moe Myint Shein

Chapter 9. XML & PHP

Web Development



XML


XML
Extensible

Markup Language


XML

data

XML


HTML

XML


XML

Introduction to XML
XML

data

HTML

Data


XML HTML

markup language

XML tags

predefined

..

XML self-descriptive


XML

W3C

XML
HTML


XML HTML


XML data


..



HTML


data

HTML

XML

XML Does not DO Anything


XML


XML


XML

Jani Tove

note

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>


self descriptive

XML

document

..

tags


Software

XML is Just Plain Text

97

Youth Dreams

97

PHP Guide Book

Moe Myint Shein

XML


plain text

Software

XML

XML

Application
XML tag


tags

application

XML

tag

<to>

<from>


XML standard
defined

tag

XML

document

XML language

predefined tags

HTML

HTML

tag

Predefined
HTML
documents

HTML

standard

tags

<p>

<h1>

XML

HTML


XML

software

hardware

XML

XML document
XML

self-describing

syntax

<?xml version="1.0" encoding="ISO-8859-1"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>


XML


XML version 1.0

encoding
(ISO-8859-1 = Latin-1/West European character set)


document

root element

document
note

<note>

to,from,heading

body

root
child elements

<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>

root element

98

Youth Dreams

98

PHP Guide Book

Moe Myint Shein

</note>

XML document
Jani Tove

note

XML documents

root element

element

element

parent


XML

elements
document tree

root

branches

elements

elements (child elements)


<root>
<child>
<subchild>.....</subchild>
</child>

</root>
parent, child, sibling

elements

level

elements

HTML

text content

attributes

XML

<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>

99

Youth Dreams

99

PHP Guide Book

Moe Myint Shein

</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

root element <bookstore>

<book> elements
<bookstore>


<book> element


<title> <author> <year>

<price>

XML Syntax Rules


XML Syntax Rules

elements

tag

HTML

elelement

<p>This is a paragraph
<p>This is another paragraph
XML

closing tag

tag

<p>This is a paragraph</p>
<p>This is another paragraph</p>

XML declaration

closing tag

..
declaration XML document

XML tags
Case Sensitive


XML
<letter> <Letter>

tag

case

<Message>This is incorrect</message>
<message>This is correct</message>
XML elements

nested


HTML


bold

italic

bold

italic

<b><i>This text is bold and italic</b></i>

100

Youth Dreams

100

PHP Guide Book

Moe Myint Shein

XML

XML

nested

<b><i>This text is bold and italic</i></b>


<i> <b>

<b>

XML elements

HTML

attributes

attribute value

XML
quote

<note date=12/11/2007>
<to>Tove</to>
<from>Jani</from>
</note>

<note date="12/11/2007">
<to>Tove</to>
<from>Jani</from>
</note>

Entity References

XML



less than < character

XML
element

error


XML parser

element

error

<message>if salary < 1000 then</message>

error

< character

entity reference

<message>if salary &lt; 1000 then</message>


XML

entity references

<

&
XML

illegal

.. greater than character


entity reference

101

Youth Dreams

101

PHP Guide Book

Moe Myint Shein

Comments in XML
XML
comment

syntax
HTML

<!This is a comment -- >


What is an XML Element?
XML document

XML elements

XML element
element

start tag element

end

tag


element

elements


element

attributes

<bookstore>
<book category="CHILDREN">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

<bookstore>
<book>

element contents

elements


<author>

text content

text

<book>
attribute


(category=CHILDREN)
XML Naming Rules
XML

letter, numbers


character

punctuation charcter

xml, XML, Xml


spaces

XML Elements are Extensible


XML elements

102

Youth Dreams

102

PHP Guide Book

Moe Myint Shein

<note>
<to>Tove</to>
<from>Jani</from>
<body>Don't forget me this weekend!</body>
</note>

Output

XML document
<to>, <from>

<body> elements

application

..
MESSAGE
To:

Tove

From: Jani
Don't forget me this weekend!

<note>
<date>2008-01-10</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

application crash

break


No

application

<to>, <from> <body>

element

output


XML


application

extend

XML Attributes
XML elements

HTML

start tag

attribute


Attribute
element

HTML

<img src=computer.gif>

src

attribute
<img> element

<img src="computer.gif">
<a href="demo.asp">
XML attribute

Quote


single quote double quote

sex

person

tag

103

Youth Dreams

103

PHP Guide Book

Moe Myint Shein

<person sex="female">

<person sex='female'>
attribute

double quote

single quote

<gangster name='George "Shotgun" Ziegler'>

character entity

<gangster name="George &quot;Shotgun&quot; Ziegler">


XML Elements vs. Attributes

<person sex="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
<person>
<sex>female</sex>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>

sex attribute


sex element

attribute

element

HTML
attribute


XML


element
attribute

My Favorite Way

XML documents

date attribute

<note date="10/01/2008">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

date element

<note>
<date>10/01/2008</date>

104

Youth Dreams

104

PHP Guide Book

Moe Myint Shein

<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
date element

<note>
<date>
<day>10</day>
<month>01</month>
<year>2008</year>
</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
XML Attributes for Metadata

elements

ID references

messages>
<note id="501">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note id="502">
<to>Jani</to>
<from>Tove</from>
<heading>Re: Reminder</heading>
<body>I will not</body>
</note>
</messages>

identifier

notes


note

metadata

attributes


data

elements

XML Validation

syntax

xml document

well formed

syntax rule

-XML document

root element

-XML tags

case sensitive

105

Youth Dreams

105

PHP Guide Book

Moe Myint Shein

-XML elements


nested

-XML attribute

quote

<?xml version="1.0" encoding="ISO-8859-1"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Valid XML Documents
valid

XML document

document type definitation (DND)


well form xml


documents

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE note SYSTEM "Note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

DOCTYPE

DTD file

DTD file
content

XML DTD
DTD


XML document

define

legal
elements

structure

<!DOCTYPE note [
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to
(#PCDATA)>
<!ELEMENT from
(#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body
(#PCDATA)>
]>
XML Schema
W3C DTD

XML Schema

support

<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to"
type="xs:string"/>
<xs:element name="from"
type="xs:string"/>
<xs:element name="heading" type="xs:string"/>

106

Youth Dreams

106

PHP Guide Book

<xs:element name="body"
</xs:sequence>
</xs:complexType>

Moe Myint Shein

type="xs:string"/>

</xs:element
XML Validator
XML document

error

XML application


error

XML document

processing


Program

W3C XML specification

XML

software

compatible

HTML
browsers
error

document


XML
error

XML

syntax

XML validator

Viewing XML Files


Raw XML file

browser


HTML page

XML files

<?xml version="1.0" encoding="ISO-8859-1"?>


- <note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Displaying XML with CSS


XML document

CSS

CD Catalog XML file

<?xml version="1.0" encoding="ISO-8859-1"?>


<?xml-stylesheet type="text/css" href="cd_catalog.css"?>
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>

107

Youth Dreams

107

PHP Guide Book

Moe Myint Shein

<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
.
.
.
.
</CATALOG>
CSS file

CATALOG
{
background-color: #ffffff;
width: 100%;
}
CD
{
display: block;
margin-bottom: 30pt;
margin-left: 0;
}
TITLE
{
color: #FF0000;
font-size: 20pt;
}
ARTIST
{
color: #0000FF;
font-size: 20pt;
}
COUNTRY,PRICE,YEAR,COMPANY
{
display: block;
color: #000000;
margin-left: 20pt;
}

CSS

format

CD catalog

108

Youth Dreams

108

PHP Guide Book

Moe Myint Shein

XML

CSS

format

W3C

XSLT

recommend

Displaying XML with XSLT


XLST

XML document

HTML

XSLT XML
recommend

style sheet language


XSLT(eXtensible Stylessheet Language
Transformations) CSS

XSLT

browser

XML

HTML

XML file

<!-- Edited by XMLSpy -->


<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>
two of our famous Belgian Waffles with plenty of real maple syrup
</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>

109

Youth Dreams

109

PHP Guide Book

Moe Myint Shein

<price>$7.95</price>
<description>
light Belgian waffles covered with strawberries and whipped cream
</description>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>
light Belgian waffles covered with an assortment of fresh berries and whipped
cream
</description>
<calories>900</calories>
</food>
<food>
<name>French Toast</name>
<price>$4.50</price>
<description>
thick slices made from our homemade sourdough bread
</description>
<calories>600</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>
two eggs, bacon or sausage, toast, and our ever-popular hash browns

110

Youth Dreams

110

PHP Guide Book

Moe Myint Shein

</description>
<calories>950</calories>
</food>
</breakfast_menu>
XSLT Style Sheet

result

XML file

<?xml version="1.0" encoding="ISO-8859-1"?>


<?xml-stylesheet type="text/xsl" href="simple.xsl"?>


XML file

XSLT file

XML

PHP
XML

PHP XML Expat Parser


PHP
Built in Expat parser PHP

XML document

pricess

What is Expat?
XML document

XML parser

XML parsers

111

Youth Dreams

111

PHP Guide Book

Moe Myint Shein

-Tree-based parser:
parser

XML document

tree structure

document

analyze

tree elements

access


Document
Object Model(DOM)

-Event-based parser: XML document

events

series


specific event

function

Expat parser

event-based parser

Event-based parsers XML document


content


Structure

event-based parser
tree-based parses

data

access

<from>Jani</from>
event

series

XML

event-based parser

-Start Element:From
-Start CDATA section,

Jani
-Close element: from
XML well-formed XML

valid XML

DTD

Expat parser

Expat
DTDs

non-validating
parser

event based

non-validating XML parser

Expat
PHP web applications


XML document

well-formed

Expat error

Installation
XML Expat parser function
PHP core

function

install

XML file

<?xml version="1.0" encoding="ISO-8859-1"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

112

Youth Dreams

112

PHP Guide Book

Moe Myint Shein

Initializing the XML Parser


PHP
XML parser

XML events

handlers

XML file

parse

<?php
//Initialize the XML parser
$parser=xml_parser_create();
//Function to use at the start of an element
function start($parser,$element_name,$element_attrs)
{
switch($element_name)
{
case "NOTE":
echo "-- Note --<br />";
break;
case "TO":
echo "To: ";
break;
case "FROM":
echo "From: ";
break;
case "HEADING":
echo "Heading: ";
break;
case "BODY":
echo "Message: ";
}
}
//Function to use at the end of an element
function stop($parser,$element_name)
{
echo "<br />";
}
//Function to use when finding character data
function char($parser,$data)
{
echo $data;
}
//Specify element handler
xml_set_element_handler($parser,"start","stop");
//Specify data handler
xml_set_character_data_handler($parser,"char");
//Open XML file
$fp=fopen("test.xml","r");
//Read data
while ($data=fread($fp,4096))
{
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}
//Free the XML parser
xml_parser_free($parser);

113

Youth Dreams

113

PHP Guide Book

Moe Myint Shein

?>


code
output

-- Note -To: Tove


From: Jani
Heading: Reminder
Message: Don't forget me this weekend!

1.

XML parser

xml_parser_create() function

2.

event handlers

function

3.

parser opening
closing tag

function

4.

xml_set_handler() function

parser character data

function

xml_set_character_data_handler()

5.

text.xml

parse


xml_parse () function

6.

error

xml_error_string()

function

XML

error

7.

xml_parser_create() function

memory allocate

xml_parser_free() function

PHP XML DOM


built-in

DOM parser

PHP

XML documents

Process

What is DOM?
XML DOM(Document Object Model) XML documents

access

standard


DOM XML document

tree structure


element
attribute

nodes

114

Youth Dreams

114

PHP Guide Book

Moe Myint Shein

XML

XML DOM

PHP XML DOM


DOM


DOM
W3C (World Wide

Web Consortium) Standard


DOM XML

HTML

document

access


DOM

-Core DOM-

document

model
-XML DOM- XML documents

model
-HTML DOM HTML documents

model

DOM document elements

object

properties

access

methods (interface)


HTML DOM

XML DOM

XML DOM

-XML

standard Object Model

-XML

standing programming interface

-Platform

Language

-W3C

115

Youth Dreams

115

PHP Guide Book

Moe Myint Shein

XML DOM
XML elements

XML DOM Nodes


DOM

XML document

node

DOM

-document

document node

-XML element

element node

-XML elements

text
text node

- attribute

attribute node

-Comments
comment nodes

DOM Example
<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>

116

Youth Dreams

116

PHP Guide Book

Moe Myint Shein

<book category="web" cover="paperback">


<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
XML
root node <bookstore >

nodes

<bookstore>

root node <bookstore>

<book> nodes


<book> node
<title>, <author>,
<year>
<price>

nodes


..

"Everyday Italian", "Giada De Laurentiis", "2005",


and "30.00"

text node

DOM processing

error

element node

element node

text node

<year>2005</year>

<year>

element node 2005

text node


2005
<year>

element

XML DOM Node Tree


XML DOM XML document

node- tree


tree

nodes

nodes

tree

access

content


element


node tree nodes


tree root node

tree

text node

books.xml

117

Youth Dreams

117

PHP Guide Book

Moe Myint Shein

<!-- Edited by XMLSpy -->


<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>

118

Youth Dreams

118

PHP Guide Book

Moe Myint Shein

<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
Node Parents, Children, and Siblings
node tree

nodes



parent, child , subling



parent node
children


level
children
siblings

-node tree

node

root

-
root

node

parent node

- node

- leaf

node

-sibling

nodes

node tree

nodes

First Child - Last Child

119

Youth Dreams

119

PHP Guide Book

Moe Myint Shein


XML

<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>
<title> element <book> element


<price> element
<book>
element

<book> element <title>, <author>, <year>,


<price>
elements

parent node

XML Parsing in PHP


DOM

PHP

XML

document

XML parser

XML parser


tree-based

event-based

Expat parser event based

DOM parser tree-based

XML

<?xml version="1.0" encoding="ISO-8859-1"?>


<from>Jani</from>
XML DOM

XML

tree structure

Level 1: XML Document


Level 2: Root element: <from>
Level 3: Text element: "Jani"
DOM XML parser
PHP core

function

install

XML file

<?xml version="1.0" encoding="ISO-8859-1"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

120

Youth Dreams

120

PHP Guide Book

Moe Myint Shein

XML parser

xml

load


output

PHP code

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");
print $xmlDoc->saveXML();
?>

code
Output

Tove Jani Reminder Don't forget me this weekend!


browser window
view source

HTML

<?xml version="1.0" encoding="ISO-8859-1"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

DOM Document Object

note.xml XML

load

saveXML() function

XML document

string

print

Looping through XML

XML parser

XML
load

<note> element

element

looping

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");
$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item)
{
print $item->nodeName . " = " . $item->nodeValue . "<br />";
}
?>

code

output

#text =
to = Tove
#text =
from = Jani
#text =
heading = Reminder
#text =
body = Don't forget me this weekend!

121

Youth Dreams

121

PHP Guide Book

Moe Myint Shein

#text =

element


text nodes

XML generate

nodes

white-space



XML DOM parser


element

PHP SimpleXML
SimpleXML PHP5

XML document

layout

element

attribute

text

DOM
Expat parser

SimpleXML element

text data

code

SimpleXML

XML document

object

Elements-

SimpleXMLElement object

attribute


level

element

array

Attributes

associative array

access


index

attribute name

Element data- element


text data

strings


element

text
node

order

SimpleXML

-XML file

read

-XML string
data

extract

-text nodes

attribute

advanced XML

Expat parser


XML DOM

PHP 5.0
SimpleXML functions
PHP core

function

install

Using SimpleXML

XML file

<?xml version="1.0" encoding="ISO-8859-1"?>


<note>

122

Youth Dreams

122

PHP Guide Book

Moe Myint Shein

<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

file
element

data

Output



1.

XML file

Load

2.


element

3.

child node

children()function

loop

4.

child node

element

data

<?php
$xml = simplexml_load_file("test.xml");
echo $xml->getName() . "<br />";
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br />";
}
?>

code

run

Output

note
to: Tove
from: Jani
heading: Reminder
body: Don't forget me this weekend!

123

Youth Dreams

123

PHP Guide Book

Moe Myint Shein

Chapter 10. Exceptiong Handling & Filter in PHP


Exception

PHP 5

error

Object Oriented

Exceptiong handling
error

code

execute

flow

exception


exception

code

(save)

code execution (custom)

exception handler function


handler save

code

run

resume

script execution

code

script

run

Error handling methods

Basic use of Exceptions


Creating a custom exception handler
Multiple exceptions
Re-throwing an exception
Setting a top level exception handler

- Exception

error

code

Basic Use of Exceptions


exception

code

execute

PHP catch

block

exception

caught

Uncaught Exception

error

catch

exception

<?php
//create function with an exception
function checkNum($number)
{
if($number>1 )
{
throw new Exception("Value must be 1 or below");
}
return true;
}

124

Youth Dreams

124

PHP Guide Book

Moe Myint Shein

//trigger exception
checkNum(2);
?>

error

Fatal

error:

Uncaught

exception

'Exception'

with

message

'Value

must

be

or

below'

in

C:\xampp\htdocs\php\1.php:7 Stack trace: #0 C:\xampp\htdocs\php\1.php(13): checkNum() #1 {main}


thrown in C:\xampp\htdocs\php\1.php on line 7
Try, throw and catch
Try, throw
catch
exception

error

exception

code

Proper exception code

code

1.Try- exception


function try block


exception

code


run

exception

exception

thrown

2.Throw-

exception

throw


catch

3. Catch- catch block

exception

exception information

object

valid code
exception

<?php
//create function with an exception
function checkNum($number)
{
if($number>1)
{
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception in a "try" block
try
{
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}
//catch exception
catch(Exception $e)

125

Youth Dreams

125

PHP Guide Book

Moe Myint Shein

{
echo 'Message: ' .$e->getMessage();
}
?>

code

error

output

Message: Value must be 1 or below

exception

throw

catch

1.

checkNum() function

exception

2.

try block

checkNum() function

4.

catch block exception


($e) object


object
exception

3.

5.

checkNum() function

exception

(thrown)

information

exception
error message
$e->getMessage()

exception object

echo

Creating a Custom Exception Class

custom exception class


PHP


exception

function

class

class
exception
class
extension

custom exception class PHP


excepton class

custom function

exception class

<?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}
$email = "someone@example...com";
try
{
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
//throw exception if email is not valid
throw new customException($email);

126

Youth Dreams

126

PHP Guide Book

Moe Myint Shein

}
}
catch (customException $e)
{
//display custom message
echo $e->errorMessage();
}
?>
class
old exception class

errorMessage()

function


old class
copy

properties
method

old class

getLine(), getFile()
getMessage()

exception class methods

exception

custom exception class

1.
2.

customException() class

Old exception class


extension

old exception class methods

properties

errorMessage()


email address invalid

function error

message

3.

$email variable

valid

email

4.

try block

execute


email

valid

exception
thrown

5.

catch block exception

error message

Multiple Exceptions

exception

script


if else block switch
nested multiple exception

exception

exception class

error message

<?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}
$email = "someone@example.com";
try
{

127

Youth Dreams

127

PHP Guide Book

Moe Myint Shein

//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
//throw exception if email is not valid
throw new customException($email);
}
//check for "example" in mail address
if(strpos($email, "example") !== FALSE)
{
throw new Exception("$email is an example e-mail");
}
}
catch (customException $e)
{
echo $e->errorMessage();
}
catch(Exception $e)
{
echo $e->getMessage();
}
?>
run

someone@example.com is an example e-mail

code

1.
2.

customException() class

Old exception class


extension

old exception class methods

properties

errorMessage()


email address invalid

function error message

3.

$email variable
valid

email

example

string

4.

try block

execute

exception

5.

example

exception

6.

catch
exception

error message

Re-throwing Exceptions

exception

thrown

catch block

exception

throw

script

user

system error

System error
coder

user

user

user friendly message

exception

re-throw

<?php
class customException extends Exception
{

128

Youth Dreams

128

PHP Guide Book

Moe Myint Shein

public function errorMessage()


{
//error message
$errorMsg = $this->getMessage().' is not a valid E-Mail address.';
return $errorMsg;
}
}
$email = "someone@example.com";
try
{
try
{
//check for "example" in mail address
if(strpos($email, "example") !== FALSE)
{
//throw exception if email is not valid
throw new Exception($email);
}
}
catch(Exception $e)
{
//re-throw exception
throw new customException($email);
}
}
catch (customException $e)
{
//display custom message
echo $e->errorMessage();
}
?>
Output
someone@example.com is not a valid E-Mail address.

1.

customException() class

Old exception class


extension

old exception class methods

properties

2.
3.

errorMessage()


email address invalid

function error message

$email variable
valid

email

example

string

4.

try block

exception

re-throw



try block

5.

email
example

string

exception

6.

catch block exception

customException

re-throws

7.

customException

error message

Set a Top Level Exception Handler


set_exception_hadnler() function

exception

user-defined
function

set

129

Youth Dreams

129

PHP Guide Book

Moe Myint Shein

<?php
function myException($exception)
{
echo "<b>Exception:</b> " , $exception->getMessage();
}
set_exception_handler('myException');
throw new Exception('Uncaught Exception occurred');
?>
output

Exception: Uncaught Exception occurred

code
catch block


top level exception handler

function

uncaught
exception

Exception

1.

Code

try block

2.

try block

throw

catch block

3.

exception class

catch block

4.

try block

catch block

exception

thrown (or rethrown)

5.

( throw)

(catch)

PHP Filter
PHP Filter

?
PHP filter

user


input

valid

filter

user imputer


validate

filter


web application

PHP filter



filter(

Filter


?
web application


Input

user

web service

application

filter

..

application

input

130

Youth Dreams

130

PHP Guide Book

Moe Myint Shein

data


filter


input filtering application

security

external data

form

Input data

Cookies

Web services

data

server variable

Database query result

Functions and Filters


variable

filter

filter function

filter_var()-

filter

variable

filter

filter_var_array()-

filter


variable

filter

filter_input- variable input

filter

filter_input_array-

input variable

filter

filter

filter_var() function


integer

valid

<?php
$int = 123;
if(!filter_var($int, FILTER_VALIDATE_INT))
{
echo("Integer is not valid");
}
else
{
echo("Integer is valid");
}
?>


code variable

filter

FILTER_VALIDATE_INT filter

Integer valid

output
Interger is valid.

integer

variable 123abc

Integer is not valid

Validating and Sanitizing

131

Youth Dreams

131

PHP Guide Book

Moe Myint Shein

filter

Validating filters

Sanitizing filters

Validating filters

user input

validate

format rule

( URL

EMAIL)

validate

FALSE

Sanitizing filters

string

character

data format rules


String
return

Options and Flags


options

flags

filters

filter options

filter

Options

flags

filter_var() function
min_range

max_range option

integer

validate

<?php
$var=300;
$int_options = array(
"options"=>array
(
"min_range"=>0,
"max_range"=>256
)
);
if(!filter_var($var, FILTER_VALIDATE_INT, $int_options))
{
echo("Integer is not valid");
}
else
{
echo("Integer is valid");
}
?>

code
options

option


associative array


flag

array

integer 300

range

code

run
Integer is not valid

Validate Input
form

input form

validate

132

Youth Dreams

132

PHP Guide Book

Moe Myint Shein

input data

filter_input ()
function

input data

filter

input variable email

PHP page

<?php
if(!filter_has_var(INPUT_GET, "email"))
{
echo("Input type does not exist");
}
else
{
if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL))
{
echo "E-Mail is not valid";
}
else
{
echo "E-Mail is valid";
}
}
?>

input

(URL)

POST Method

1.

POST type
url input

2.

sanitize(valid

character)

$url variable

Input string http://www.moemyintshein.com/

sanitizing

http://www.moemyintshein.com

Filter Multiple Inputs


Form


input fileld


filter_var

filter_input function

filter_var_array

filter_input_array

function

GET variable

filter

filter_input_array() function

GET variable

<?php
$filters = array
(
"name" => array
(

133

Youth Dreams

133

PHP Guide Book

Moe Myint Shein

"filter"=>FILTER_SANITIZE_STRING
),
"age" => array
(
"filter"=>FILTER_VALIDATE_INT,
"options"=>array
(
"min_range"=>1,
"max_range"=>120
)
),
"email"=> FILTER_VALIDATE_EMAIL,
);
$result = filter_input_array(INPUT_GET, $filters);
if (!$result["age"])
{
echo("Age must be a number between 1 and 120.<br />");
}
elseif(!$result["email"])
{
echo("E-Mail is not valid.<br />");
}
else
{
echo("User input is valid");
}
?>

(name,age,email)

Input

GET method

1.

input variable

array


input variables

filter

2.

filter_input_array() function

GET input variable

array

3.

valid input

$result variable

age, email variable

input

invalid

filter_input_array() function

input variable FALSE

filter_input_array() function

parameter array

single filter ID

parameter single filter ID

input array

filter

filter

parameter array

134

(age input variable

) array key

input variable

associative array

array

filter ID

filter, flag

option

array

Youth Dreams

134

PHP Guide Book

Moe Myint Shein

Using Filter Callback


user defined function

FILTER_CALLBACK filter

filter

data filtering

User defined function

PHP function

whitespaces

user created function

<?php
function convertSpace($string)
{
return str_replace("_", " ", $string);
}
$string = "Peter_is_a_great_guy!";
echo filter_var($string, FILTER_CALLBACK,
array("options"=>"convertSpace"));
?>
output

Peter is a great guy!

1.

whitespaces

fuction

2.

FILTER_CALLBACK filter

function

array

filter_var() function

135

Youth Dreams

135

PHP Guide Book

Moe Myint Shein

Conclusion

English

PHP

Moe Myint Shein


Email: moemyintsheinster@gmail.com
Web: www.moemyintshein.com

136

Youth Dreams

136

You might also like