COMP519 Web Programming
Lecture 25: PHP (Part 7)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
1 Classes
Defining and Instantiating a Class
Visibility
Class Constants
Static Properties and Methods
Destructors
Inheritance
Interfaces
Introspection Functions
2 The PDO Class
Introduction
Connections
Queries and Processing of Results
Prepared Statements
Transactions
3 Revision and Further Reading
COMP519 Web Programming Lecture 25 Slide L25 1
Classes Defining and Instantiating a Class
Defining and Instantiating a Class
PHP is an object-oriented language with classes
A class can be defined as follows:
class iden tifi er {
pro pe rty _defi nit io ns
fun ct ion _defi nit io ns
}
The class name identifier is case-sensitive
The body of a class consists of property definitions and function definitions
The function definitions may include the definition of a constructor
An object of a class is created using
new ide ntif ier ( arg1 ,arg2 ,...)
where arg1,arg2,... is a possibly empty list of arguments passed to
the constructor of the class identifier
COMP519 Web Programming Lecture 25 Slide L25 2
Classes Defining and Instantiating a Class
A Closer Look at Class Definitions
In more detail, the definition of a class
typically looks as follows
class iden tifi er {
# Prope rtie s
vis $ att rib1
...
vis $ att ribN = value
# Cons truc tor
funct ion __ cons tru ct (p1 ,...) {
stat emen ts
}
# Methods
vis func tion met hod1 (p1 ,...) {
stat emen ts
}
vis func tion met hodN (p1 ,...) {
stat emen ts
}
}
Every instance obj of this
class will have attributes
attrib1,. . . and methods
method1(), . . . accessible
as obj->attrib1 and
obj->method1(a1...)
__construct is the
constructor of the class and
will be called whenever
new identifier(a1,...)
is executed
vis is a declaration of the
visibility of each attribute
and method
COMP519 Web Programming Lecture 25 Slide L25 3
Classes Defining and Instantiating a Class
A Closer Look at Class Definitions
The pseudo-variable $this is available when a method is called from
within an object context and is a reference to the calling object
Inside method definitions, $this can be used to refer to the properties
and methods of the calling object
The object operator -> is used to access methods and properties of the
calling object
class Rect angle {
prot ected $ height ;
prot ected $ width ;
funct ion __ cons tru ct ( $height , $width ) {
$this - > wi dth = $wi dth ;
$this - > hei ght = $height ;
}
}
COMP519 Web Programming Lecture 25 Slide L25 4
Classes Visibility
Visibility
Properties and methods can be declared as
public accessible everywhere
private accessible only within the same class
protected accessible only within the class itself and
by inheriting and parent classes
For properties, a visibility
declaration is required
For methods, a visibility
declaration is optional
; by default, methods
are public
Accessing a private or
protected property /
method outside its visibility
is a fatal error
class Vis {
public $publi c = 1;
privat e $priv ate = 2;
prot ected $pro tect ed = 3;
prot ected funct ion proFc () {}
privat e funct ion priFc () {}
}
$v = new Vis ();
echo $v -> public ; # pri nts 1
echo $v -> privat e ; # Fatal Error
echo $v -> prot ecte d ; # Fatal Error
echo $v -> priFc (); # Fatal Error
echo $v -> proFc (); # Fatal Error
COMP519 Web Programming Lecture 25 Slide L25 5
Classes Class Constants
Constants
Classes can have their own constants and
constants can be declared to be public, private or protected
; by default, class constants are public
vis const iden tifi er = value ;
Accessing a private or protected constant outside its visibility
is a fatal error ; execution of the script stops
Class constants are allocated once per class,
and not for each class instance
Class constants are accessed using the scope resolution operator ::
class M yClass {
const SIZE = 10;
}
echo MyC lass :: SIZE ; # prints 10
$o = new MyC lass ();
echo $o :: SIZE ; # prints 10
COMP519 Web Programming Lecture 25 Slide L25 6
Classes Static Properties and Methods
Static Properties and Methods
Class properties or methods can be declared static
Static class properties and methods are accessed (via the class) using
the scope resolution operator ::
Static class properties cannot be accessed via an instantiated
class object, but static class methods can
Static class method have no access to $this
class E mploy ee {
static $ t ota lNumber = 0;
public $name ;
funct ion __ cons tru ct ( $name ) {
$this - > name = $name ;
Emplo yee :: $tot alN umbe r ++;
} }
$e1 = new E mploy ee (" Ada " );
$e2 = new E mploy ee (" Ben " );
echo Em ploye e :: $ t ota lNum ber # print s 2
COMP519 Web Programming Lecture 25 Slide L25 7
Classes Destructors
Destructors
A class can have a destructor method __destruct that will be called as
soon as there are no references to a particular object
class E mploy ee {
static $ t ota lNumber = 0;
public $name ;
funct ion __ cons tru ct ( $name ) {
$this - > name = $name ;
Emplo yee :: $tot alN umbe r ++;
}
funct ion __ dest ruct () {
Emplo yee :: $t otalNumber --;
}
}
$e1 = new E mploy ee (" Ada " );
$e2 = new E mploy ee (" Ben " );
echo Em ploye e :: $ t ota lNum ber # print s 2
$e1 = null ;
echo Em ploye e :: $ t ota lNum ber # print s 1
COMP519 Web Programming Lecture 25 Slide L25 8
Classes Inheritance
Inheritance
In a class definition it is possible to specify one parent class from which
a class inherits constants, properties and methods:
class ide ntif ier1 extends iden tif ier2 { ... }
The constructor of the parent class is not automatically called it must
be called explicitly from the child class
Inherited constants, properties and methods can be overridden by
redeclaring them with the same name defined in the parent class
The declaration final can be used to prevent a method from being
overriden
Using parent:: it is possible to access overridden methods or static
properties of the parent class
Using self:: it is possible to access static properties and methods of
the current class
COMP519 Web Programming Lecture 25 Slide L25 9
Classes Inheritance
Inheritance
class Rectan gle {
pro tecte d $heig ht ;
pro tecte d $width ;
fu n ctio n __ constr u ct ( $height , $w idth ) {
$this - > he igh t = $h e ight ;
$this - > width = $ wi dth ;
}
fu n ctio n area () {
re turn $this -> width * $this - > h eig ht ;
} }
class S quare e xten ds Recta n gle {
fu n ctio n __ constr u ct ( $ si ze ) {
pa rent :: _ _const r uct ( $size , $ size );
} }
$rt1 = new R ectan g le (3 ,4);
echo " \ $ rt1 area = " ,$rt1 -> area (), " \ n " ;
$sq1 = new Squa re (5) ;
echo " \ $ sq1 area = " ,$sq1 -> area (), " \ n " ;
$rt1 area = 12
$sq1 area = 25
COMP519 Web Programming Lecture 25 Slide L25 10
Classes Interfaces
Interfaces
Interfaces specify which methods a class must implement without
providing an implementation
Interfaces are defined in the same way as a class with the keyword
class replaced by interface
All methods in an interface must be declared public
A class can declare that it implements one ore more interfaces
using the implements keyword
inte rface Shape {
public fun ction area ();
}
class Rect angle impl emen ts Shape {
...
}
COMP519 Web Programming Lecture 25 Slide L25 11
Classes Introspection Functions
Introspection Functions
There are functions for inspecting objects and classes:
bool class_exists(string class)
returns TRUE iff a class class exists
class_exists('Rectangle') # returns TRUE
string get_class(object obj)
returns the name of the class to which an object belongs
get_class($sq1) # returns 'Square'
bool is_a(object obj, string class)
returns TRUE iff obj is an instance of class named class
is_a($sq1,'Rectangle') # returns TRUE
bool method_exists(object obj,string method)
returns TRUE iff obj has a method named method
method_exists($sq1,'area') # returns TRUE
COMP519 Web Programming Lecture 25 Slide L25 12
Classes Introspection Functions
Introspection Functions
There are functions for inspecting objects and classes:
bool property_exists(object obj,string property)
returns TRUE iff object has a property named property
property_exists($sq1,'size') # returns FALSE
get_object_vars(object)
returns an array with the accessible non-static properties of object
mapped to their values
get_object_vars($e2)
# returns ["name" => "Ben"]
get_class_methods(class)
returns an array of method names defined for class
get_class_methods('Square')
# returns ["__construct", "area"]
COMP519 Web Programming Lecture 25 Slide L25 13
The PDO Class Introduction
The PDO Class
The PHP Data Objects (PDO) extension defines an interface for
accessing databases in PHP
Various PDO drivers implement that interface for specific
database management systems
PDO_MYSQL implements the PDO interface for MySQL 3.x to 5.x
PDO_SQLSRV implements the PDO interface for MS SQL Server and
SQL Azure
COMP519 Web Programming Lecture 25 Slide L25 14
The PDO Class Connections
Connections
Before we can interact with a DBMS we need to establish a connection
to it
A connection is established by creating an instance of the PDO class
The constructor for the PDO class accepts arguments that specify the
database source (DSN), username, password and additional options
$pdo = new PDO ( dsn , username , password , optio ns );
Upon successful connection to the database, the constructor returns an
instance of the PDO class
The connection remains active for the lifetime of that PDO object
Assigning NULL to the variable storing the PDO object destroys it and
closes the connection
$pdo = NULL
COMP519 Web Programming Lecture 25 Slide L25 15
The PDO Class Connections
Connections: Example
# C onne ctio n inf orma tion for the De part men tal MySQL Server
$host = " st uddb . csc . liv . ac . uk " ;
$user = " sgfsurn "; # your Uni vers ity usernam e
$passw d = " --- --- -"; # your MySQL server ac count pas sword
$db = " sg fsurn "; # your Uni vers ity us ernam e
$char set = " ut f8mb4 ";
$dsn = " mysql : host = $host ; dbname = $db ; char set = $ ch arset ";
# Usefu l op tions
$opt = array (
PDO :: A TTR _ERR MOD E => PDO :: ERR MODE_ EXCEP TION ,
PDO :: ATT R_D EF AUL T_ FET CH _MO DE = > PDO :: FETCH _ASSOC ,
PDO :: A TT R_E MU LAT E_ PRE PAR ES => false
);
try {
$pdo = new PDO ( $dsn , $user , $passwd , $opt );
} catch ( PD OEx cept ion $e ) {
echo ' Conne ctio n failed : ' ,$e -> getM essa ge ();
}
COMP519 Web Programming Lecture 25 Slide L25 16
The PDO Class Queries and Processing of Results
Queries
The query() method of PDO objects can be used to execute
an SQL query
$result = $pdo->query(statement)
$result = $pdo->query("SELECT * FROM meetings")
query() returns the result set (if any) of the SQL query as a
PDOStatement object
The exec() method of PDO objects executes an SQL statement,
returning the number of rows affected by the statement
$rowNum = $pdo->exec(statement)
$rowNum = $pdo->exec("DELETE * FROM meetings")
COMP519 Web Programming Lecture 25 Slide L25 17
The PDO Class Queries and Processing of Results
Processing Result Sets
To get a single row as an array from a result set stored in a
PDOStatement object, we can use the fetch() method
By default, PDO returns each row as an array indexed by
the column name and 0-indexed column position in the row
$row = $result -> fet ch ()
array ( ' slot ' => 1 ,
' name ' => ' Michael North ' ,
' email ' => 'M. Nor th@ stu dent . live rpoo l . ac . uk ' ,
0 => 1,
1 => ' M ichael North ' ,
2 => ' M . Nort h@s tude nt . l iver pool . ac . uk ' )
After the last call of fetch() the result set should be released using
$rows = $ result -> clo seC urso r ()
To get all rows as an array of arrays from a result set stored in a
PDOStatement object, we can use the fetchAll() method
$rows = $ result -> fetc hAll ()
COMP519 Web Programming Lecture 25 Slide L25 18
The PDO Class Queries and Processing of Results
Processing Result Sets
We can use a while-loop together with the fetch() method to iterate
over all rows in a result set
while ( $row = $result - > fetch ()) {
echo " Slot : " , $row [ " slot " ], " <br >\ n ";
echo " Name : " , $row [ " name " ], " <br >\ n ";
echo " Email : " , $row [ " email "]," <br >< br >\ n" ;
}
Alternatively, we can use a foreach-loop
foreac h ( $result as $ row ) {
echo " Slot : " , $row [ " slot " ], " <br >\ n ";
echo " Name : " , $row [ " name " ], " <br >\ n ";
echo " Email : " , $row [ " email "]," <br >< br >\ n" ;
}
fetch() uses a cursor that moves through the rows in a result set and
does not reset at the end
; store the result set in an array first (e.g., using fetchAll() ),
then iterate over the array as often as you want
COMP519 Web Programming Lecture 25 Slide L25 19
The PDO Class Queries and Processing of Results
Processing Result Sets
Using bindColumn() we can bind a variable a particular column in the
result set from a query
columns can be specified by number (starting with 1!)
columns can be specified by name (matching case)
Each call to fetch() and fetchAll() will then update all the
variables that are bound to columns
The binding needs to be renewed after each query execution
$result - > bindCo lumn (1 , $ slot ); # bind by colum n no
$result - > bindCo lumn (2 , $ name );
$result - > bindCo lumn ( ' email ' , $ em ail ); # bind by co lumn name
while ( $row = $result - > fetch ( PDO :: FET CH_B OUN D )) {
echo " Slot : " , $slot , " <br >\ n" ;
echo " Name : " , $name , " <br >\ n" ;
echo " Email : " , $email ," <br ><br >\ n ";
}
COMP519 Web Programming Lecture 25 Slide L25 20
The PDO Class Prepared Statements
Prepared Statements
The use of parameterised prepared statements is preferable over queries
Prepared statements are are parsed, analysed, compiled and optimised
only once
Prepared statements can be executed repeatedly with different
arguments
Arguments to prepared statements do not need to be quoted and
binding of parameters to arguments will automatically prevent SQL
injection
PDO can emulate prepared statements for a DBMS that does not
support them
MySQL supports prepared statements natively, so PDO emulation
should be turned off
$pdo - > s etA ttri but e ( PDO :: AT TR_E MULA TE_ PREP ARES , FALSE );
COMP519 Web Programming Lecture 25 Slide L25 21
The PDO Class Prepared Statements
Prepared Statements: SQL Templates
Using a prepared statement requires three steps
1 Preparing a statement using a SQL template containing parameters
2 Binding the parameters to values
3 Executing the prepared statements
COMP519 Web Programming Lecture 25 Slide L25 22
The PDO Class Prepared Statements
Prepared Statements: SQL Templates
An SQL template is an SQL query (as a string) possibily containing
either
named parameters of the form :name, where name is a PHP identifier, or
question marks ?
for which values will be substituted when the query is executed
$tpl1 = " select slot from me eting s where
name =: name and email =: email ";
$tpl2 = " select slot from me eting s where name =? ";
The PDO method prepare() turns an SQL template into a
prepared statement (by asking the DBMS to do so)
on success, a PDOStatement object is returned
on failure, FALSE or an error will be returned
$stmt1 = $pdo -> prepar e ( $tpl1 );
$stmt2 = $pdo -> prepar e ( " se lect * from fruit where col =? " );
COMP519 Web Programming Lecture 25 Slide L25 23
The PDO Class Prepared Statements
Prepared Statements: Binding
We can bind the parameters of a PDOStatement object to a value
using the bindValue() method
Named parameters are bound by name
Question mark parameters are bound by position (starting from 1!)
the datatype of the value can optionally be declared
(to match that of the corresponding database field)
the value is bound to the parameter at the time bindValue() is executed
$stmt1 -> bind Valu e ( ' : name ' ,' Ben ' ,PDO :: PAR AM_ST R );
$email = ' bj1@liv . ac . uk ' ;
$stmt1 -> bind Valu e ( ' : email ' , $ ema il );
$stmt2 -> bind Valu e (1 ,20 , PDO :: PAR AM_IN T );
COMP519 Web Programming Lecture 25 Slide L25 24
The PDO Class Prepared Statements
Prepared Statements: Binding
We can bind the parameters of a PDOStatement object to a variable
using the bindParam() method
Named parameters are bound by name
Question mark parameters are bound by position (starting from 1!)
the datatype of the value can optionally be declared
(to match that of the corresponding database field)
the variable is bound to the parameter as a reference
a value is only substituted when the statement is executed
$name = ' Ben ';
$stmt1 -> bind Para m ( ' : name ' ,$name , PDO :: PARA M_ST R );
$stmt1 -> bind Para m ( ' : email ' , $ ema il );
$email = ' bj1@liv . ac . uk ' ;
$slot = 20;
$stmt2 -> bind Para m (1 , $ slot , PDO :: PAR AM_IN T );
It is possible to mix bindParam() and bindValue()
COMP519 Web Programming Lecture 25 Slide L25 25
The PDO Class Prepared Statements
Prepared Statements: Execution
Prepared statements are executed using execute() method
Parameters must
previously have been bound using bindValue() or bindParam(), or
be given as an array of values to execute
; take precedence over previous bindings
; are bound using bindValue()
execute() returns TRUE on success or FALSE on failure
On success, the PDOStatement object stores a result set (if appropriate)
$stmt1 -> execut e ();
$stmt1 -> execut e ( array ( ' : name ' => ' Eve ' , ': email ' => $ email ));
$stmt2 -> execut e ( array (10));
COMP519 Web Programming Lecture 25 Slide L25 26
The PDO Class Transactions
Transactions
There are often situations where a single ‘unit of work’ requires a
sequence of database operations
; e.g., bookings, transfers
By default, PDO runs in ”auto-commit” mode
; successfully executed SQL statements cannot be ‘undone’
To execute a sequence of SQL statements whose changes are
only committed at the end once all have been successful or
rolled back otherwise,
PDO provides the methods
beginTransaction()
commit()
rollBack()
COMP519 Web Programming Lecture 25 Slide L25 27
The PDO Class Transactions
Transactions
To support transactions, PDO provides the methods
beginTransaction()
turns off auto-commit mode; changes to the database are not
committed until commit() is called
returns TRUE on success or FALSE on failure
throws an exception if another transaction is already active
commit()
changes to the database are made permanent;
auto-commit mode is turned on
returns TRUE on success or FALSE on failure
throws an exception if no transaction is active
rollBack()
discard changes to the database; auto-commit mode is restored
returns TRUE on success or FALSE on failure
throws an exception if no transaction is active
COMP519 Web Programming Lecture 25 Slide L25 28
The PDO Class Transactions
Transactions: Example (Part 1)
We want to transfer £10.50 from one account at a bank to another,
but only if the payer has enough money
Either both subtracting the money from one account and adding it to
another should be successful or neither
$b alan ce = a rray ();
// store Balan c e ( $id , $b )
// $id : acc oun t id
// $b : ba lanc e for the acc oun t with id $ id
// maps $ id to $b in the ar ray $ ba lanc e
fu ncti on sto reBal a nce ($id , $b ) {
gl obal $b a lan ce ;
$b alan ce [ $id ] = $ b ;
}
$pdo = new PDO ( ' mysql : host =...; dbname =... ' , ' ... ' , ' ... ' ,
arra y ( PDO :: ATTR _ ERRMO DE => PDO :: ERRMO DE_E XCEP TION ,
PDO :: ATTR_E M U L ATE_PR E P A RES => false ));
try {
// Det ail s of the t rans a ctio n : payer , payee , amount
$p ayer Id = 1; $ paye eId = 2; $ paym e n tAmou n t = 10.50;
COMP519 Web Programming Lecture 25 Slide L25 29
The PDO Class Transactions
Transactions: Example (Part 2)
$pdo - > b e ginTr a n sacti o n ();
// Obtain pa yee 's and p ayer ' s account bala nces
// and lock ac ces s to both rec ord s
$s ql1 = " select id , b ala nce fr om acco unt s wh ere id =? or id =? for up dat e " ;
$s tmt = $pdo -> pr epa re ( $sql1 );
$stmt - > exe cute ( array ( $ payerId , $ paye eId ));
// St ore the data r etr i eve d from the da taba se in $ bal ance array
$stmt - > fetc hAl l ( PDO :: FETCH _FUNC , ' s toreB alanc e ' );
// Ch eck whe the r ther e is eno ugh money in the p ayer ' s account
if ( $ bal a nce [ $ p aye rId ] < $p a yment A mount ) {
echo " Ins u ffic i ent fun ds in paye r ' s ac count ";
} else {
$sql = " UP DATE a ccou nts SET bal anc e = bala nce + ? WH ERE id = ?" ;
$s tmt = $pdo -> pr epa re ( $sql );
// Inc reas e balanc e of pay ee ' s a ccount by pay men t am moun t
$stmt - > exe cute ( array ( $ pay men tAmo unt , $ pay e eId ));
// Dec reas e balanc e of pay er ' s a ccount by pay men t am moun t
$stmt - > exe cute ( array ( - $ pay men tAmo unt , $ pay e rId ));
}
COMP519 Web Programming Lecture 25 Slide L25 30
The PDO Class Transactions
Transactions: Example (Part 3)
// Commit the tra nsac t ion ( w het her money was tran sfer r ed or not )
$pdo - > com mit ();
} c atch ( P D OExc e ptio n $e ) {
// Some thin g w ent wro ng at some poin t
echo " Error : " ,$e -> get M essa ge () , " < br >\ n " ;
// Roll back the t r ansa c tion
$pdo - > r oll Back ();
}
COMP519 Web Programming Lecture 25 Slide L25 31
Revision and Further Reading
Revision and Further Reading
Read
Language Reference: Classes and Objects
http://php.net/manual/en/language.oop5.php
The PDO Class
http://php.net/manual/en/class.pdo.php
of P. Cowburn (ed.): PHP Manual. The PHP Group, 25 Oct 2019.
http://uk.php.net/manual/en [accessed 26 Oct 2019]
COMP519 Web Programming Lecture 25 Slide L25 32