sqlite/ sqlite3beraldi/psd2011/slides/php_4.pdf · sqlite/ sqlite3 • light and fast, shipped with...

Post on 26-Aug-2020

11 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

SQLite / SQLite3

• Light and fast, shipped with php5

• No dedicated servers are required

• Procedural and object oriented APIs

• Cons: Lock mechanism is not very efficient

Open/create a dbresource sqlite_open ( string $filename [, int $mode [, string &$error_message ]] )

Opens a SQLite database or creates the database if it does not exist.

<?phpif ($db = sqlite_open("SIMPLE.DB",0666,&$error))

<?php$db = new SQLiteDatabase("SIMPLE.DB", &$error);if ($db = sqlite_open("SIMPLE.DB",0666,&$error))

print("DB OPENED...."."\n");else die($error);

?>

SIMPLE.DB

$db = new SQLiteDatabase("SIMPLE.DB", &$error);if ($db) echo “DB OPENED....";else die($error);

?>

Create a table

$create_query = "CREATE TABLE PRODUCTS (id integer primary key,description,quantity integer

Sql statment

Two types: integer and text

Executes a result-less query against a given database

bool queryExec ( string $query [, string &$error_msg ] )

id description quantity

quantity integer)";$db->queryExec($create_query);

db

PRODUCTS

Two types: integer and text(similar to varchar)

Insert a row

$query = "INSERT INTO PRODUCTS (id,description,quantity) VALUES (1,'DVD',1)";$db->queryExec($query);

id Description quantity

1 DVD 1

db

PRODUCTS

Update/delete

$db->queryexec('DELETE FROM PRODUCTS WHERE id=2');

$db->queryexec('UPDATE PRODUCTS SET id=19 WHERE id=4');

Fetch results

query fetch, fetch all,

SQLiteResult

seek rewind, current…

unbufferedquery

SQLiteUnbuffered

forward only, much faster

Fetch results$q = "SELECT * FROM PRODUCTS;";

$qr = $db->query($q); //Executes a query against a given database and returns a result handle

$r = $qr->fetchAll();//Fetches all rows from a result set as an array of arrays

foreach ($r as $entry) {

echo $entry['id'].' '.$entry['description'].' '.$entry['quantity'].'<br>';

}

1 DVD 1

LAB /Project (shopping cart 2)

• PRODUCT table

– View content

– Insert items

– Delete items – Delete items

• Password DB

– User registration

– User authentication

PHP Communicationstring file_get_contents ( string $filename [ …])

Reads entire file into a string

<?php/* Identical to above, explicitly naming FILE scheme */$localfile = file_get_contents("file:///home/bar/foo.txt");

/* Read remote file from www.example.com using HTTP */$httpfile = file_get_contents("http://www.example.com/foo.txt");

/* Read remote file from www.example.com using HTTPS */$httpsfile = file_get_contents("https://www.example.com/foo.txt");

/* Read remote file from ftp.example.com using FTP */$ftpfile = file_get_contents("ftp://user:pass@ftp.example.com/foo.txt");

/* Read remote file from ftp.example.com using FTPS */$ftpsfile = file_get_contents("ftps://user:pass@ftp.example.com/foo.txt");?>

Example

• Flickr is a web site that allows to share

personal photos

• Free account for 90 days

• API with different formats• API with different formats

– Request: REST,XML-RPC,SOAP

– Reply: REST,XML-RPC,SOAP,JSON,PHP

Flickr’s application end-points

• http://api.flickr.com/services/rest/

• http://api.flickr.com/services/soap/

• http://api.flickr.com/services/xmlrpc/

• http://api.flickr.com/services/upload/ • http://api.flickr.com/services/upload/

• http://api.flickr.com/services/replace/

http://api.flickr.com/services/rest/?method=...&name=value...

end-point-type

REST format is the simplest way; it uses the HTTP POST method

CLIENT SERVER

Reply, different format: REST,XML-RPC,SOAP,JSON,PHP

PHP_Serial

Example of API call

flickr.photos.getInfo

api_key (Mandatory)

Your API application key.

In Parameters:

Your API application key.

photo_id (Mandatory)

The id of the photo to get information for.

secret (optional)

The secret for the photo.

If the correct secret is passed then permissions checking is skipped, unless photo is shared.

Out Parameters:

info with different format…

Example of reply

An example: invoking a REST end-point from PHP code

$param = array('api_key' => 'e568d81ac2ac47e943673641e037be8 c','method' => 'flickr.photos.getInfo','photo_id' => '11111','format' => 'php_serial',);

$encoded_params = array();

Parameters

urlencode

•Reply in php serial format

foreach ($param as $k => $v)

$encoded_params [ ] = urlencode($k).'='.urlencode($v);

$url = "http://api.flickr.com/services/rest/?".implode('&',$encoded_params);

http://api.flickr.com/services/rest/?api_key=e568d81ac2ac47e943673641e037be8&method=flickr.photos.getInfo&photo_id=11111&format=php_serial

$url

•non-alphanumeric as %

sign two hex digits

•spaces as plus (+) signs.

•Join array elements with

a string,

•& used as glue string

implode

urlencode

Serializationstring serialize ( mixed $value )

Generates a storable

representation of a value

mixed unserialize ( string $str )

Creates a PHP value from

a stored representation

$ans = file_get_contents($url);

$ans_obj = unserialize($ans);

if ($ans_obj['stat']=='ok') {

echo $ans_obj['photo']['id'].'<br>';

echo $ans_obj['photo']['title'] ['_content'];

Invoke method

Transform

format into an

associative array

echo $ans_obj['photo']['description']['_content'];

echo $ans_obj['photo']['dates']['taken'];

}

XML-RPC in PHP

• XML-based Remote Procedure Call

– Specifica sviluppata nel 1998

• Trasporta messaggi XML tramite il protocollo HTTP (POST)

– Firewall friendly – Firewall friendly

• E’ indipendente dal linguaggio di programmazione

• Supporta un insieme minimo di tipi (comuni a tutti imoderni linguaggi),.. ma non estendibile

XML-RPC

• La specifica consiste di tre parti

• Data Model

• Struttura messaggio di richiesta

• Struttura messaggio di rispostaStruttura messaggio di risposta

XML in pillole

• XML (eXtensible Markup Language) è un linguaggio derivatodal linguaggio SGML (Standard Generalized MarkupLanguage), da cui deriva anche HTML.

• In questi linguaggi, il concetto chiave è quello di Markup(annotazione) mediante cui si specificano aspetti dei dati.(annotazione) mediante cui si specificano aspetti dei dati.

• In XML il markup definisce la struttura logica del dato (mentrein HTML, solo l’apparenza)

XML in pillole

• Un documento XML ha struttura ad albero

• I dati appaiono in elementi che, oltre a contenere il dato veroe proprio in codifica testuale (ex. ASCII), contengonoannotazioni sotto forma di TAG di descrizione della strutturadel dato ed, opzionalmente, coppie attributo-valoredel dato ed, opzionalmente, coppie attributo-valore

Data Model

• Scalari

• Strutture

• Array

Tipi scalari

Tag Type Example

<i4> or <int> four-byte signed integer -12

<boolean> 0 (false) or 1 (true) 1

<string> string hello world

<double> double-precision signed floating point

number

-12.214

<dateTime.iso8601> date/time 20101504T09:30:00

<base64> base64-encoded binary eW91IGNhbid0IHJlYWQgdGhpcyE=

Tipo Struct

<struct>

<member>

<name>lowerBound</name>

<value><i4>18</i4></value>

</member>

<member>

<name>upperBound</name>

<value><i4>139</i4></value>

</member>

</struct>

Array

<array>

<data>

<value><i4>12</i4></value>

<value><string>Egypt</string></value>

<value><boolean>0</boolean></value>

<value><i4>-31</i4></value><value><i4>-31</i4></value>

</data>

</array>

Struttura messaggio di richiesta

• Elemento root: methodCall

• Ogni elemento root contiene un elemento

MethodName ed uno params

• L’elemento MethodName contiene il nome della • L’elemento MethodName contiene il nome della

procedura da chiamare

• L’elemento params contiene l’elenco dei parametri

della procedura

Esempio<?xml version="1.0"?><methodCall>

<methodName>PSD</methodName><params>

<param><value><i4>123</i4></value>

</param><param>

<value><double>12.3</double></value><value><double>12.3</double></value></param>

</params></methodCall>

Esempio<?xml version="1.0"?><methodCall>

<methodName>PSD</methodName><params>

<param><value><i4>123</i4></value>

</param><param>

<value><double>12.3</double></value>

methodCall

PSD

methodName

params

param valuei4

123<value><double>12.3</double></value></param>

</params></methodCall>

param valuedouble

123

12.3

Esempio<?xml version="1.0"?><methodCall>

<methodName>PSD</methodName><params>

<param><value><i4>123</i4></value>

</param><param>

<value><double>12.3</double></value>

methodCall

PSD

methodName

params

param valuei4

123<value><double>12.3</double></value></param>

</params></methodCall>

param valuedouble

123

12.3

methodName

params

paramparam

doublei4

methodCall

XML è veicolato da HTTP

Esempio richiesta completa

POST /xmlrpc HTTP 1.0

User-Agent: …

Host: …

Content-type: text/xml

Content-length: ..

<?xml version=“1.0”?>

<methodCall>

<methodName>AreaCerchio</methodName>

<params><param><value><double>12.2</double></value><param><params>

</methodCall>

Messaggio di risposta

• Può contenere la risposta (un singolo parametro)

oppure indicare il fallimento con una stringa di

diagnosi

Esempio risposta

<?xml version="1.0"?>

<methodResponse>

<params>

<param>

<value><i4>1</i4></value><value><i4>1</i4></value>

</param>

</params>

</methodResponse>

Messaggio di fault<?xml version="1.0"?>

<methodResponse>

<fault>

<value>

<struct>

<member>

<name>faultCode</name>

<value><int>4</int></value>

</member></member>

<member>

<name>faultString</name>

<value><string>Too many parameters.</string></value>

</member>

</struct>

</value>

</fault>

</methodResponse>

Semantica

• Chiamate sincrone

– La richiesta è bloccante. Il chiamante viene bloccato finchènon riceve il documento XML di risposta

– L’indirizzo del destinatario (‘end-point’) è quello dellaconnessione HTTP

• Stateless

– Non ci sono meccanismi nativi per propagare lo stato fradue chiamate consecutive allo stesso end-point

– Lo ‘stato’ dovrebbe essere inviato come parametro di unachiamata…

top related