程序代写代做代考 database SQL COMP284 Scripting Languages – Handouts (8 on 1)

COMP284 Scripting Languages – Handouts (8 on 1)

COMP284 Scripting Languages
Lecture 13: PHP (Part 5)

Handouts (8 on 1)

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

COMP284 Scripting Languages Lecture 13 Slide L13 – 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 identifier {

property_definitions

function_definitions

}

• 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 identifier(arg1 ,arg2 ,…)

where arg1,arg2,… is a possibly empty list of arguments passed to
the constructor of the class identifier

COMP284 Scripting Languages Lecture 13 Slide L13 – 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 identifier {

# Properties

vis $attrib1

vis $attribN = value

# Constructor

function __construct(p1 ,…) {

statements

}

# Methods

vis function method1(p1 ,…) {

statements

}

vis function methodN(p1 ,…) {

statements

}

}

• 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

COMP284 Scripting Languages Lecture 13 Slide L13 – 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 Rectangle {

protected $height;

protected $width;

function __construct($height ,$width) {

$this ->width = $width;

$this ->height = $height;

}

}

COMP284 Scripting Languages Lecture 13 Slide L13 – 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 $public = 1;

private $private = 2;

protected $protected = 3;

protected function proFc() {}

private function priFc() {}

}

$v = new Vis ();

echo $v->public; # prints 1

echo $v->private; # Fatal Error

echo $v->protected; # Fatal Error

echo $v->priFc (); # Fatal Error

echo $v->proFc (); # Fatal Error

COMP284 Scripting Languages Lecture 13 Slide L13 – 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 identifier = 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 MyClass {

const SIZE = 10;

}

echo MyClass ::SIZE; # prints 10

$o = new MyClass ();

echo $o::SIZE; # prints 10

COMP284 Scripting Languages Lecture 13 Slide L13 – 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 Employee {

static $totalNumber = 0;

public $name;

function __construct($name) {

$this ->$name = $name;

Employee :: $totalNumber ++;

} }

$e1 = new Employee(“Ada”);

$e2 = new Employee(“Ben”);

echo Employee :: $totalNumber # prints 2

COMP284 Scripting Languages Lecture 13 Slide L13 – 7

Classes Destructors

Destructors

• A class can have a destructor method __destruct that will be called as
soon as there are no other references to a particular object

class Employee {

static $totalNumber = 0;

public $name;

function __construct($name) {

$this ->name = $name;

Employee :: $totalNumber ++;

}

function __destruct () {

Employee :: $totalNumber –;

}

}

$e1 = new Employee(“Ada”);

$e2 = new Employee(“Ben”);

echo Employee :: $totalNumber # prints 2

$e1 = null;

echo Employee :: $totalNumber # prints 1

COMP284 Scripting Languages Lecture 13 Slide L13 – 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 identifier1 extends identifier2 { … }

• 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

COMP284 Scripting Languages Lecture 13 Slide L13 – 9

Classes Inheritance

Inheritance: Example

class Rectangle {

protected $height;

protected $width;

function __construct($height ,$width) {

$this ->width = $width;

$this ->height = $height;

}

function area() {

return $this ->width * $this ->height;

} }

class Square extends Rectangle {

function __construct($size) {

parent :: __construct($size ,$size);

} }

$rt1 = new Rectangle (3,4);

echo “\$rt1 area = “,$rt1 ->area(),”\n”;

$sq1 = new Square (5);

echo “\$sq1 area = “,$sq1 ->area(),”\n”;

$rt1 area = 12

$sq1 area = 15

COMP284 Scripting Languages Lecture 13 Slide L13 – 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

interface Shape {

public function area ();

}

class Rectangle implements Shape {

}

COMP284 Scripting Languages Lecture 13 Slide L13 – 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

COMP284 Scripting Languages Lecture 13 Slide L13 – 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”]

COMP284 Scripting Languages Lecture 13 Slide L13 – 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

COMP284 Scripting Languages Lecture 13 Slide L13 – 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 ,options );

• 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

COMP284 Scripting Languages Lecture 13 Slide L13 – 15

The PDO Class Connections

Connections: Example

# Connection information for the Departmental MySQL Server

$host = “mysql”;

$user = “ullrich”;

$passwd = “——-“;

$db = “ullrich”;

$charset = “utf8mb4”;

$dsn = “mysql:host=$host;dbname=$db;charset=$charset”;

# Useful options

$opt = array(

PDO:: ATTR_ERRMODE => PDO:: ERRMODE_EXCEPTION ,

PDO:: ATTR_DEFAULT_FETCH_MODE => PDO:: FETCH_ASSOC ,

PDO:: ATTR_EMULATE_PREPARES => false

);

try {

$pdo = new PDO($dsn ,$user ,$passwd ,$opt);

} catch (PDOException $e) {

echo ’Connection failed: ’,$e->getMessage ();

}

COMP284 Scripting Languages Lecture 13 Slide L13 – 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”)

COMP284 Scripting Languages Lecture 13 Slide L13 – 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 ->fetch ()

array(’slot’ => 1,

’name’ => ’Michael North ’,

’email’ => ’M.North@student.liverpool.ac.uk’,

0 => 1,

1 => ’Michael North’,

2 => ’M.North@student.liverpool.ac.uk’)

• After the last call of fetch() the result set should be released using
$rows = $result ->closeCursor ()

• The 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 ->fetchAll ()

COMP284 Scripting Languages Lecture 13 Slide L13 – 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”], “
\n”;

echo “Name: “,$row[“name”], “
\n”;

echo “Email: “,$row[“email”],”

\n”;

}

• Alternatively, we can use a foreach-loop
foreach($result as $row) {

echo “Slot: “,$row[“slot”], “
\n”;

echo “Name: “,$row[“name”], “
\n”;

echo “Email: “,$row[“email”],”

\n”;

}

COMP284 Scripting Languages Lecture 13 Slide L13 – 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 ->bindColumn (1, $slot); # bind by column no

$result ->bindColumn (2, $name);

$result ->bindColumn(’email’, $email ); # bind by column name

while ($row = $result ->fetch(PDO:: FETCH_BOUND )) {

echo “Slot: “,$slot , “
\n”;

echo “Name: “,$name , “
\n”;

echo “Email: “,$email ,”

\n”;

}

COMP284 Scripting Languages Lecture 13 Slide L13 – 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 ->setAttribute(PDO:: ATTR_EMULATE_PREPARES , FALSE );

COMP284 Scripting Languages Lecture 13 Slide L13 – 21

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 meetings where

name=:name and email =:email”;

$tpl2 = “select slot from meetings where name=?”;

• The PDO method prepare() turns an SQL template into 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 ->prepare($tpl1 );

$stmt2 = $pdo ->prepare(“select * from fruit where col=?”);

COMP284 Scripting Languages Lecture 13 Slide L13 – 22

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 ->bindValue(’:name’,’Ben’,PDO:: PARAM_STR );

$email = ’bj1@liv.ac.uk’;

$stmt1 ->bindValue(’:email’,$email );

$stmt2 ->bindValue (1,20,PDO:: PARAM_INT );

COMP284 Scripting Languages Lecture 13 Slide L13 – 23

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 ->bindParam(’:name’,$name ,PDO:: PARAM_STR );

$stmt1 ->bindParam(’:email’,$email );

$email = ’bj1@liv.ac.uk’;

$slot = 20;

$stmt2 ->bindParam(1,$slot ,PDO:: PARAM_INT );

• It is possible to mix bindParam() and bindValue()

COMP284 Scripting Languages Lecture 13 Slide L13 – 24

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 ->execute ();

$stmt1 ->execute(array(’:name’ => ’Eve’, ’:email’ => $email ));

$stmt2 ->execute(array (10));

COMP284 Scripting Languages Lecture 13 Slide L13 – 25

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()

COMP284 Scripting Languages Lecture 13 Slide L13 – 26

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

COMP284 Scripting Languages Lecture 13 Slide L13 – 27

The PDO Class Transactions

Transactions: Example
$pdo = new PDO(’mysql:host =…; dbname =…’,’…’,’…’,

array(PDO:: ATTR_ERRMODE => PDO:: ERRMODE_EXCEPTION ,

PDO:: ATTR_EMULATE_PREPARES => false ));

$pdo ->beginTransaction ();

try{

$userId = 1; $paymentAmount = 10.50;

// Query 1: Attempt to insert a payment record

$sql = “INSERT INTO payments (user_id , amount) VALUES (?, ?)”;

$stmt = $pdo ->prepare($sql);

$stmt ->execute(array($userId ,$paymentAmount ));

// Query 2: Attempt to update the user’s account

$sql = “UPDATE accounts SET balance = balance + ? WHERE id = ?”;

$stmt = $pdo ->prepare($sql);

$stmt ->execute(array($paymentAmount ,$userId ));

// Commit the transaction

$pdo ->commit ();

} catch(Exception $e){

echo $e->getMessage ();

// Rollback the transaction

$pdo ->rollBack ();

}
Based on http://thisinterestsme.com/php-pdo-transaction-example/

COMP284 Scripting Languages Lecture 13 Slide L13 – 28

The PDO Class Transactions

Revision

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 M. Achour, F. Betz, A. Dovgal, et al: PHP Manual. The PHP Group,
2017. http://uk.php.net/manual/en [accessed 07 Dec 2017]

COMP284 Scripting Languages Lecture 13 Slide L13 – 29

PHP: PDO transaction example.


http://php.net/manual/en/language.oop5.php
http://php.net/manual/en/class.pdo.php
http://uk.php.net/manual/en

Lecture 13
Classes
Defining and Instantiating a Class
Visibility
Class Constants
Static Properties and Methods
Destructors
Inheritance
Interfaces
Introspection Functions

The PDO Class
Introduction
Connections
Queries and Processing of Results
Prepared Statements
Transactions