SQL PHP Delphi HTML XML - Istituto Guglielmo · PDF fileSQL PHP Delphi HTML XML ......

71
ISTITUTO TECNICO INDUSTRIALE STATALE “G. Chilesotti” - Thiene (VI) DIPARTIMENTO DI INFORMATICA E SISTEMI G G u u i i d d a a r r a a p p i i d d a a a a l l l l a a s s i i n n t t a a s s s s i i d d i i S S Q Q L L P P H H P P D D e e l l p p h h i i H H T T M M L L X X M M L L Anno Scolastico 2004/2005

Transcript of SQL PHP Delphi HTML XML - Istituto Guglielmo · PDF fileSQL PHP Delphi HTML XML ......

Page 1: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

ISTITUTO TECNICO INDUSTRIALE STATALE “G. Chilesotti” - Thiene (VI)

DIPARTIMENTO DI INFORMATICA E SISTEMI

GGuuiiddaa rraappiiddaa aallllaa ssiinnttaassssii ddii SSQQLL PPHHPP

DDeellpphhii HHTTMMLL XXMMLL

Anno Scolastico 2004/2005

Page 2: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

Indice

Indice..................................................... 2 Sintassi (semplificata) SQL ........................ 1

Tipi e domini................................................1 cast ................................................................. 1 create domain ................................................... 1 alter domain ..................................................... 2 drop domain ..................................................... 2

Comandi per la definizione dello schema ..........2 create schema................................................... 2 drop schema..................................................... 2 create table ...................................................... 2 alter table......................................................... 2 drop table......................................................... 3 create view....................................................... 3 drop view ......................................................... 3 create assertion................................................. 3 drop assertion................................................... 3

Interrogazioni in SQL ....................................3 select............................................................... 3 Interrogazioni di tipo insiemistico ........................ 4

Manipolazione dei dati in SQL.........................4 insert ............................................................... 4 delete .............................................................. 4 update ............................................................. 4

Stored Procedures e Triggers (Interbase).........5 Stored Procedures ............................................. 5 Triggers ........................................................... 5 Generatori in Interbase ...................................... 6

Indici..........................................................6 create index...................................................... 6 drop index ........................................................ 6

Autorizzazioni in SQL ....................................6 Concessione dei privilegi..................................... 6 Revoca dei privilegi............................................ 6

Istruzioni principali PHP............................. 7 Sintassi Fondamentale ..................................7

Modi per uscire dalla modalità HTML .................... 7 Separazione delle istruzioni................................. 8 Commenti......................................................... 8

Variabili ......................................................8 Predefined variables........................................... 8

Operatori ....................................................9 Precedenza degli operatori.................................. 9 Operatori aritmetici...........................................10 Operatori bitwise ..............................................10 Operatori di confronto .......................................10 Operatori di controllo errori................................10 Operatori di esecuzione .....................................10 Operatori di incremento/decremento...................10 Operatori logici.................................................11 Operatori di stringa...........................................11

Strutture di controllo .................................. 11 if ....................................................................11 else ................................................................11 elseif (oppure else if) ........................................11 Sintassi alternativa per le strutture di controllo ....11 while...............................................................12 do..while .........................................................12 for ..................................................................12 foreach ...........................................................12 break..............................................................12 continue..........................................................13 switch .............................................................13 return .............................................................13 require() .........................................................13 include() .........................................................13 require_once() .................................................14 include_once() .................................................14

Funzioni.................................................... 14 Funzioni definite dall’utente ...............................14 Argomenti delle funzioni ....................................14 Costruire argomenti passati per riferimento .........15 Liste di argomenti a lunghezza variabile ..............15 Valori restituiti .................................................15

Funzioni di Mail .......................................... 15 mail ................................................................15

Funzioni Matematiche ................................. 16 abs .................................................................16 acos................................................................16 asin ................................................................16 atan................................................................16 base_convert ...................................................16 bindec.............................................................16 ceil .................................................................16 cos .................................................................16 decbin.............................................................17 dechex............................................................17 decoct.............................................................17 deg2rad ..........................................................17 exp.................................................................17 floor ...............................................................17 fmod...............................................................17 getrandmax .....................................................17 hexdec............................................................18 is_finite...........................................................18 is_infinite ........................................................18 is_nan.............................................................18 lcg_value.........................................................18 log10 ..............................................................18 log..................................................................18 max................................................................18 min.................................................................19 octdec.............................................................19

Page 3: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

pi ...................................................................19 pow ................................................................19 rad2deg ..........................................................19 rand................................................................19 round..............................................................19 sin ..................................................................20 sqrt ................................................................20 srand ..............................................................20 tan .................................................................20

Funzioni InterBase...................................... 20 ibase_blob_add ................................................20 ibase_blob_cancel ............................................20 ibase_blob_close ..............................................20 ibase_blob_create ............................................20 ibase_blob_echo...............................................20 ibase_blob_get.................................................21 ibase_blob_import ............................................21 ibase_blob_info ................................................21 ibase_blob_open ..............................................21 ibase_close......................................................21 ibase_commit ..................................................21 ibase_connect ..................................................21 ibase_errmsg ...................................................21 ibase_execute ..................................................22 ibase_fetch_object............................................22 ibase_fetch_row ...............................................22 ibase_field_info ................................................22 ibase_free_query..............................................22 ibase_free_result..............................................22 ibase_num_fields..............................................22 ibase_pconnect ................................................22 ibase_prepare ..................................................23 ibase_query .....................................................23 ibase_rollback ..................................................23 ibase_timefmt..................................................23 ibase_trans......................................................23

Funzioni MySQL.......................................... 23 mysql_affected_rows ........................................23 mysql_change_user ..........................................23 mysql_client_encoding ......................................24 mysql_close.....................................................24 mysql_connect .................................................24 mysql_create_db..............................................24 mysql_data_seek..............................................24 mysql_db_name...............................................25 mysql_drop_db ................................................25 mysql_errno ....................................................25 mysql_error .....................................................25 mysql_escape_string ........................................25 mysql_fetch_array............................................26 mysql_fetch_assoc ...........................................26 mysql_fetch_field .............................................26 mysql_fetch_lengths .........................................26 mysql_fetch_object...........................................27 mysql_fetch_row ..............................................27 mysql_field_flags..............................................27 mysql_field_len ................................................27

mysql_field_name ............................................27 mysql_field_seek..............................................27 mysql_field_table .............................................27 mysql_field_type ..............................................28 mysql_free_result.............................................28 mysql_get_client_info .......................................28 mysql_get_host_info.........................................28 mysql_get_proto_info .......................................28 mysql_get_server_info......................................28 mysql_info.......................................................28 mysql_insert_id................................................29 mysql_list_dbs .................................................29 mysql_list_fields...............................................29 mysql_list_processes ........................................29 mysql_list_tables..............................................29 mysql_num_fields ............................................29 mysql_num_rows .............................................30 mysql_pconnect ...............................................30 mysql_ping......................................................30 mysql_query....................................................30 mysql_real_escape_string .................................31 mysql_result....................................................31 mysql_select_db ..............................................31 mysql_stat ......................................................31 mysql_tablename .............................................31 mysql_thread_id ..............................................32 mysql_unbuffered_query...................................32

Funzioni Stringa ......................................... 33 addcslashes .....................................................33 addslashes ......................................................33 bin2hex...........................................................33 chop ...............................................................33 chr .................................................................33 chunk_split ......................................................33 convert_cyr_string............................................33 count_chars.....................................................34 crc32 ..............................................................34 crypt...............................................................34 echo ...............................................................34 explode ...........................................................35 fprintf .............................................................35 htmlspecialchars ..............................................35 implode...........................................................36 join.................................................................36 ltrim ...............................................................36 md5................................................................36 number_format ................................................36 ord .................................................................37 parse_str.........................................................37 print ...............................................................37 printf ..............................................................37 rtrim...............................................................37 sprintf.............................................................37 sscanf .............................................................38 str_pad ...........................................................38 str_repeat .......................................................38 str_replace ......................................................38

Page 4: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

str_shuffle .......................................................39 str_word_count ................................................39 strchr..............................................................39 strcmp ............................................................39 strlen ..............................................................39 strpos .............................................................39 strrchr.............................................................39 strrev..............................................................40 strtok..............................................................40 strtolower........................................................40 strtoupper .......................................................40 strtr ................................................................40 substr_count....................................................40 substr_replace .................................................41 substr .............................................................41 trim ................................................................41 ucfirst .............................................................41 ucwords ..........................................................41 wordwrap ........................................................42

Componenti data-aware Delphi ................ 43 Componenti ADO........................................ 43

TADOConnection ..............................................43 TADOCommand................................................45 TADOTable ......................................................47 TADOQuery......................................................49

Componenti Interbase................................. 50 TIBDatabase ....................................................50 TIBTransaction .................................................50

TIBTable .........................................................51 TIBQuery.........................................................52 TIBDataSet......................................................53

Principali tag HTML ................................. 55 Elementi di base ........................................ 55 Sfondi e colori............................................ 55

Principali colori.................................................55 Caratteri speciali ........................................ 55 Formattazione del testo............................... 56 Collegamenti ed immagini ........................... 56 Segni di paragrafo e separatori .................... 57 Liste......................................................... 57 Tabelle ..................................................... 57 Moduli ...................................................... 58 Frame ...................................................... 59

ComPort ............................................... 60 Componenti SOCKET............................... 61

TClientSocket ............................................ 62 TServerSocket ........................................... 64

XML...................................................... 66 Struttura documento XML............................ 66 Schema di validità documento XML ............... 66 Componente TXMLDocument ....................... 66

Componente IOPort ................................ 67 Simbologia LAN...................................... 67

Page 5: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

1 SQL

Sintassi (semplificata) SQL

Tipi e domini STRINGHE DI CARATTERI

CHARACTER(n)

oppure CHAR(n) Stringa di lunghezza fissa di esattamente n caratteri (n>0). CHAR equivale a CHAR(1)

CHARACTER VARYING(n)

oppure VARCHAR(n) Stringa di lunghezza variabile fino a n caratteri (n>0)

stringhe di bit (introdotte da SQL-2)

BIT(n) Stringa di un numero fisso di n bit (n>0) → usato per i flag. BIT equivale a BIT(1)

BIT VARYING(n) Stringa di lunghezza variabile fino a n bit (n>0)

TIPI NUMERICI ESATTI

NUMERIC(p,q)

Numero decimale, p cifre e il segno, con un numero q di cifre dopo la virgola (0<=q<=p,p>0), la precisione è esattamente di p cifre.

Es.: con NUMERIC(6,3) si potranno rappresentare i numeri tra –999,999 a +999,999

NUMERIC(p) equivale a NUMERIC(p,0)

NUMERIC il sistema usa un valore caratteristico dell'implementazione

DECIMAL(p,q)

oppure DEC(p,q)

Numero decimale, m cifre e il segno, con un numero q di cifre dopo la virgola (0<=q<=p<=m,p>0), la precisione è di almeno p cifre (cioè l'implementazione può adottare più cifre) DECIMAL(p) equivale a DECIMAL (p,0) DECIMAL il sistema usa un valore caratteristico dell'implementazione

INTEGER

oppure INT intero con segno (implementation defined)

SMALLINT intero con segno (implementation defined)

TIPI NUMERICI APPROSSIMATI

FLOAT(p) Numero rappresentato con virgola mobile con la precisione per la mantissa di p cifre (esempio: 0,17E1015). FLOAT equivale a FLOAT(p1) CON p1 “implementation defined”

REAL equivale a FLOAT(p2) CON p2 “implementation defined”

DOUBLE PRECISION equivale a FLOAT(p3) CON p3 “implementation defined”

date e ora (introdotte da SQL-2)

DATE data

TIME ora

TIMESTAMP data e ora

cast

cast(espressione as tipo)

create domain

create domain nome_dominio [as] tipo [default <valore_default> ] [not null] [check(condizione_check)] <condizione_check> ::= VALUE <operatore> val | VALUE [not] between val and val | VALUE [not] like val | VALUE [not] in ( val {, val } ) | VALUE is[not] null | [not] exists( <selezione> ) | not <condizione_check> | <condizione_check> or <condizione_check>

Page 6: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

2 SQL

| <condizione_check> and <condizione_check> <valore_default> ::= costante | user | null <operatore> ::= < | > | = | <> | <= | >= | like

alter domain

alter domain nome_dominio set default <valore_default> | drop default | add constraint check(nome_condizione_ check) | drop constraint <valore_default> ::= costante | user | null

drop domain

drop domain nome_dominio [restrict | cascade]

Comandi per la definizione dello schema

create schema

create schema [ nome_schema ] [ [authorization] nome_utente] definizione_degli_elementi_dello_schema

drop schema drop schema nome_schema [restrict | cascade]

create table

create table nome_tabella ( nome_colonna tipo_colonna [not null] { , nome_colonna tipo_colonna [not null] } { , <vincolo_tabella> } ) <vincolo_tabella> ::= primary key ( lista_colonne ) | unique ( lista_colonne ) | foreign key (lista_colonne) references nome_tabella [( lista_colonne ) ] [on delete <tipo_comportamento>] [on update <tipo_comportamento>] | check ( <condizione_check> ) <tipo_comportamento> ::= no action | cascade | set default | set null

alter table

alter table nome_tabella add nome_colonna tipo_colonna [not null] | drop nome_colonna | add [constraint nome_vincolo] def_vincolo | drop constraint nome_vincolo

Page 7: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

3 SQL

drop table

drop table nome_tabella [restrict | cascade]

create view

create view [( lista_nomi_colonne )] nome_vista as <selezione>

drop view

drop view nome_vista [restrict | cascade]

create assertion

create assertion nome_vincolo check (condizione)

drop assertion

drop assertion nome_vincolo

Interrogazioni in SQL

select

<selezione> ::= select [distinct | all] <lista_clausola_selezione> from <riferimento_tabella> [[as] identificatore] {, < riferimento_tabella> [[as] identificatore] } [where <condizione_ricerca>] [group by nome_colonna {, nome_colonna } [having <condizione_ricerca>] [order by <lista_ordinamento>] <lista_clausola_selezione> ::= * | identificatore.* | <val> [as] identificatore] {, <val> [as] identificatore] } <val> ::= [identificato.]nome_colonna | null | costante | espressione | :variabile | <funzione> <funzione> ::= count (* | [all] <val> | distinct <val>) | sum ([all] <val> | distinct <val>) | avg ([all] <val> | distinct <val>) | max ([all] <val> | distinct <val>) | min ([all] <val> | distinct <val>) | cast (<val> as tipo) | upper (<val>) <riferimento_tabella> ::= nome_tabella | nome_vista | stored_procedure | <tabella_giunzione> <tabella_giunzione> ::= nome_tabella <tipo_join> join nome_tabella on <condizione> | (<tabella_giunzione>) <tipo_join> ::= [inner] join | left outer | right outer | full outer

Page 8: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

4 SQL

<condizione_ricerca> ::= <val> <operatore> <val> | (<selezione_a_unico_valore>)} | <val> <operatore> (<selezione_a_unico_valore>) | <val> [not] between <val> and <val> | <val> [not] like <val> | <val> [not] in (<val> {,<val> } | <selezione>) | <val> is [not] null | <val> <operatore> <quantificatore>(<selezione>) | exists (<selezione>) | ( <condizione_ricerca> ) | not <condizione_ricerca> | <condizione_ricerca> or <condizione_ricerca> | <condizione_ricerca> and <condizione_ricerca> <quantificatore> ::= all | some | any <operatore> ::= {= | < | > | <= | >= | !< | !> | <> | !=} <lista_ordinamento> ::= nome_colonna [asc | desc] {,<lista_ordinamento>}

Interrogazioni di tipo insiemistico selezione_1 <operazione_insimistica> [ all ] selezione_2 <operazione_insimistica> ::= union | intersect | except

gli operatori seguono le seguenti regole:

• le clausole select che vengono combinate con l'operatore devono avere lo stesso numero di espressioni, e le espressioni che vengono posizionate una sotto l'altra nel risultato finale devono avere tipi compatibili;

• le clausole select non dovrebbero contenere distinct; quando viene usato un operatore insiemistico vengono eliminate automaticamente le righe doppie e quindi l'aggiunta di distinct è superflua;

• è possibile usare gli operatori insiemistici con le interrogazioni nidificate;

• la clausola all viene utilizzata per ottenere anche le righe doppie

Manipolazione dei dati in SQL

insert

insert into nome_tabella [ ( lista_colonne ) ] values( lista_valori ) | <selezione>

delete

delete from nome_tabella [ where <condizione> ]

update

update nome_tabella set nome_colonna = espressione { , nome_colonna = espressione } [ where <condizione> ]

Page 9: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

5 SQL

Stored Procedures e Triggers (Interbase)

Stored Procedures

create procedure nome_procedura [ ( param <tipo_dato> {,param <tipo_dato> } ) ] [returns ( param <tipo_dato> {,param <tipo_dato> } )] as <corpo_procedura>

<corpo_procedura> ::= [<lista_dichiarazione_variabili>] <blocco>

<lista_dichiarazione_variabili> ::= declare variable var <tipo_dato>; { declare variable var <tipo_dato>; } <blocco> ::= begin <istruzione_composta> { <istruzione_composta> } end <istruzione_composta> ::= <blocco> | istruzione; <tipo_dato> ::= smallint | integer | float | double precision | < decimal | numeric > [(precisione [, scala])] | < date | time | timestamp > | < char | character | character varying | varchar > | [(int)] [character set charname] | < nchar | national character | national char > [varying] [(int)]

Triggers

create trigger nome_trigger for { nome_tabella | nome_vista } [ active | inactive ] < before | after > < delete | insert | update > [ position numero ] as <corpo_trigger>

<corpo_trigger> ::= [<lista_dichiarazione_variabili>] <blocco>

<lista_dichiarazione_variabili> ::= declare variable var <tipo_dato>; { declare variable var <tipo_dato>; } <blocco> ::= begin <istruzione_composta> { <istruzione_composta> } end <istruzione_composta> ::= <blocco> | istruzione;

Page 10: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

6 SQL

Generatori in Interbase Un generatore è una variabile intera globale disponibile nel database (quindi deve avere un nome univoco nell’ambito dello schema del database). Per creare un generatore si usa l’istruzione seguente:

create generator nome_generatore

inizialmente il generatore ha valore nullo. Per impostare un generatore ad uno specifico valore usare:

set generator nome_generatore to valore

Una volta creato un generatore, è possibile utilizzare la funzione gen_id per aggiornare il valore del generatore con uno step specificato:

gen_id (nome_generatore, step) questa funzione incrementa il valore corrente del generatore specificato dello step e ritorna il nuovo valore al generatore.

Indici

create index

create [unique] index nome_indice on nome_tabella (lista_colonne) drop index

drop index nome_indice

Autorizzazioni in SQL

Concessione dei privilegi

grant <elenco_privilegi> on [ nome_tabella | nome_vista ] to <elenco_utenti> [ with grant option ] <elenco_privilegi> ::= select | insert [(<nome_colonna>)] | update [(<nome_colonna>)] | delete [(<nome_colonna>)] | references [(<nome_colonna>)] <elenco_utenti> ::= nome_utente {, nome_utente } | public

Revoca dei privilegi revoke [grant option for] <elenco_privilegi> on [ nome_tabella | nome_vista ] from <elenco_utenti> [ restrict | cascade ]

Page 11: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

7 PHP

Istruzioni principali PHP

Sintassi Fondamentale

Modi per uscire dalla modalità HTML Quando il PHP inizia a esaminare un file, visualizzerà il contenuto del file sino a quando non incontra uno dei tag speciali indicanti l'inizio del codice da interpretare come istruzioni PHP. A questo punto il parser eseguirà tutto il codice trovato sino a quando non incontrerà i tag di chiusura, che indicano al parser di tornare alla modalità di visualizzazione. Questo meccanismo permette di inserire codice PHP all'interno di codice HTML: tutto ciò che si trova all'esterno dei tag PHP sarà lasciato inalterato, mentre tutto ciò che si trova all'interno sarà eseguito come codice PHP.

Esistono 4 set di tag che possono essere utilizzati per delimitare blocchi di codice PHP. Soltanto due di questi (<?php. . .?> e <script language="php">. . .</script>) sono sempre disponibili; gli altri possono essere attivati o disattivati tramite il file di configurazione php.ini. Sebbene i tag brevi o quelli in stile ASP possano essere pratici, il supporto di questi non è garantito in tutte le versioni. Quindi, se si intende inserire codice PHP all'interno di testi XMl o XHTML, occorre utilizzare <?php. . .?> per essere conformi allo standard XML.

I tag supportati dal PHP sono:

1. <?php echo("se si vogliono produrre documenti XHTML o XML, si utilizzi questo modo\n"); ?> 2. <? echo ("questo è il più semplice, ovvero come istruzione SGML\n"); ?> <?= espressione ?> Questa è un'abbreviazione per "<? echo espressione ?>" 3. <script language="php"> echo ("alcuni editor (tipo FrontPage) non amano le istruzioni di elaborazione"); </script> 4. <% echo ("Opzionalmente puoi utilizzare tag nello stile ASP"); %> <%= $variable; # Questo &egrave; una abbreviazione per "<%echo .." %>

Il primo, <?php. . .?>, è il metodo preferenziale, dato che permette l'utilizzo del PHP all'interno di codice conforme a specifiche XML come XHTML.

Il secondo metodo è disponibile solo se sono stati abilitati i tags abbreviati. Ciò può essere impostato sia utilizzando la funzione short_tags() (solo PHP 3), sia abilitando nel file di configurazione del PHP l'opzione short_open_tag, oppure compilando il PHP utilizzando l'opzione --enable-short-tags nel comando configure. Sebbene siano abilitati nel php.ini-dist riilasciato, l'uso dei tag brevi è vivamente sconsigliato.

Il quarto modo è disponibile solo se sono stati attivati nel file di configurazione i tag in stile ASP tramite l'opzione asp_tags.

Il tag di chiusura di un blocco include il carattere di 'a capo' immediatamente seguente, se presente. Inoltre, il tag di chiusura viene considerato automaticamente come punto e virgola; pertanto non occorre inserire il punto e virgola alla fine dell'ultima riga del blocco php.

Il PHP permette strutture tipo le seguenti:

<?php if ($expression) { ?> <strong>Questa è vera.</strong> <?php } else { ?> <strong>Questa è falsa.</strong> <?php } ?>

Questo esempio agisce come atteso, poichè il PHP rileva il tag di chiusura ?>, e da questo punto, inizia a dare in output tutto ciò che trova fino a quando non rileva un'altro tag di apertura. Certamente l'esempio dato è macchinoso, ma per l'output di grossi blocchi di testo, l'uscire dalla modalità di parsing PHP, è generalmente più efficiente piuttosto che inviare il testo tramite ripetute funzioni echo() o print().

Page 12: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

8 PHP

Separazione delle istruzioni Le istruzioni sono separate come nel C o in Perl - ogni istruzione termina con un punto e virgola.

Il tag di chiusura (?>) implica anche la fine di un'istruzione, perciò le seguenti sono equivalenti: <?php echo "Questo &grave; un test"; ?> <?php echo "Questo &grave; un test" ?>

Commenti Il PHP supporta i commenti dei linguaggi C, C++ e della shell Unix. Per esempio: <?php echo "Questo &grave; un test"; // Questo &egrave; un commento su una linea nella stile c++ /* Questo &egrave; un commento su pi&ugrave; linee ancora un'altra linea di commento */ echo "Questo &egrave; un altro test"; echo "Un ultimo test"; # Questo &egrave; un commento stile shell Unix ?>

Lo stile di commento su "una linea", attualmente commenta solo fino alla fine della linea o del blocco corrente di codice PHP. <h1>Questo &egrave; un <?# echo "semplice";?> esempio.</h1> <p>L'intestazione qui sopra dir&agrave; 'Questo &egrave; un esempio'.

Occorre fare attenzione nel non annidare i commenti di stile C, situazione che si presenta quando si commentano larghi blocchi di codice. <?php /* echo "Questo &egrave; un test"; /* Questo commento causer&agrave; dei problemi */ */ ?>

Lo stile di commento su linea singola commenta il testo fino alla fine della riga oppure alla fine del blocco di codice PHP, dipende da cosa si incontra prima. Questo significa che il codice HTML posizionato dopo // ?> SARA' visualizzato: ?> indica di uscire dal modo PHP e di ritornare in modalità HTML, e, quindi, // non hanno più effetto.

Variabili Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

Nota: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255 (0x7f-0xff).

In PHP 3, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see the chapter on Expressions.

PHP 4 offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa. This also means that no copying is performed; thus, the assignment happens more quickly. However, any speedup will likely be noticed only in tight loops or when assigning large arrays or objects.

To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable).

One important thing to note is that only named variables may be assigned by reference.

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in Perl 'Z'+1 turns into 'AA', while in C 'Z'+1 turns into '[' { ord('Z') == 90, ord('[') == 91 ).

Predefined variables PHP provides a large number of predefined variables to any script which it runs. Many of these variables, however, cannot be fully documented as they are dependent upon which server is running, the version and setup of the server, and other factors. Some of these variables will not be available when PHP is run on the command line. For a listing of these variables, please see the section on Reserved Predefined Variables.

Attenzione: In PHP 4.2.0 and later, the default value for the PHP directive register_globals is off. This is a major change in PHP. Having register_globals off affects the set of predefined variables available in the global scope. For example, to get DOCUMENT_ROOT you'll use $_SERVER['DOCUMENT_ROOT'] instead of $DOCUMENT_ROOT, or $_GET['id'] from the URL http://www.example.com/test.php?id=3 instead of $id, or $_ENV['HOME'] instead of $HOME.

For related information on this change, read the configuration entry for register_globals, the security chapter on Using Register Globals , as well as the PHP 4.1.0 and 4.2.0 Release Announcements.

Using the available PHP Reserved Predefined Variables, like the superglobal arrays, is preferred.

Page 13: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

9 PHP

From version 4.1.0 onward, PHP provides an additional set of predefined arrays containing variables from the web server (if applicable), the environment, and user input. These new arrays are rather special in that they are automatically global--i.e., automatically available in every scope. For this reason, they are often known as 'autoglobals' or 'superglobals'. (There is no mechanism in PHP for user-defined superglobals.) The superglobals are listed below; however, for a listing of their contents and further discussion on PHP predefined variables and their natures, please see the section Reserved Predefined Variables. Also, you'll notice how the older predefined variables ($HTTP_*_VARS) still exist.

Variable variables: Superglobals cannot be used as variable variables. If certain variables in variables_order are not set, their appropriate PHP predefined arrays are also left empty.

Superglobals Description

$GLOBALS Contains a reference to every variable which is currently available within the global scope of the script. The keys of this array are the names of the global variables. $GLOBALS has existed since PHP 3.

$_SERVER Variables set by the web server or otherwise directly related to the execution environment of the current script. Analogous to the old $HTTP_SERVER_VARS array (which is still available, but deprecated).

$_GET Variables provided to the script via HTTP GET. Analogous to the old $HTTP_GET_VARS array (which is still available, but deprecated).

$_POST Variables provided to the script via HTTP POST. Analogous to the old $HTTP_POST_VARS array (which is still available, but deprecated).

$_COOKIE Variables provided to the script via HTTP cookies. Analogous to the old $HTTP_COOKIE_VARS array (which is still available, but deprecated).

$_FILES Variables provided to the script via HTTP post file uploads. Analogous to the old $HTTP_POST_FILES array (which is still available, but deprecated). See POST method uploads for more information.

$_ENV Variables provided to the script via the environment. Analogous to the old $HTTP_ENV_VARS array (which is still available, but deprecated).

$_REQUEST Variables provided to the script via any user input mechanism, and which therefore cannot be trusted. The presence and order of variable inclusion in this array is defined according to the variables_order configuration directive. This array has no direct analogue in versions of PHP prior to 4.1.0. See also import_request_variables(). Nota: When running on the command line , this will not include the argv and argc entries; these are present in the $_SERVER array.

$_SESSION Variables which are currently registered to a script's session. Analogous to the old $HTTP_SESSION_VARS array (which is still available, but deprecated). See the Session handling functions section for more information.

Operatori

Precedenza degli operatori La seguente tabella fornisce una lista della precedenza degli operatori con gli operatori a più bassa precedenza listati prima. Associatività Operatori sinistra , sinistra or sinistra xor sinistra and destra print sinistra = += -= *= /= .= %= &= |= ^= ~= <<= >>= sinistra ? : sinistra || sinistra && sinistra | sinistra ^ sinistra & non associativi == != === !== non associativi < <= > >= sinistra << >> sinistra + - . sinistra * / % destra ! ~ ++ -- (int) (float) (string) (array) (object) @ destra [ non associativi new

Page 14: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

10 PHP

Operatori aritmetici Esempio Nome Risultato $a + $b Addizione La somma di $a e $b. $a - $b Sottrazione La differenza di $a e $b. $a * $b Moltiplicazione il prodotto di $a e $b. $a / $b Divisione Quoziente di $a e $b. $a % $b Modulo Il resto di $a diviso da $b.

L'operatore di divisione ("/") restituisce un valore float in ogni caso, anche se i due operandi sono interi (oppure stringhe che vengono convertite in interi).

Operatori bitwise Esempio Nome Risultato $a & $b And Sono impostati ad ON i bit che sono ON sia in $a che in $b. $a | $b Or Sono impostati ad ON i bit che sono ON in $a oppure in $b. $a ^ $b Xor Sono impostati ad ON i bit che sono ON in $a oppure in $b na non quelli che sono entrambi ON. ~ $a Not Sono impostati ad ON i bit che sono OFF in $a, e viceversa. $a << $b Shift left Sposta i bit di $a a sinistra di $b passi (ogni passo significa "moltiplica per due") $a >> $b Shift right Sposta i bit di $a a destra di $b passi (ogni passo significa "dividi per due")

Operatori di confronto Esempio Nome Risultato $a == $b Uguale TRUE se $a è uguale a $b. $a === $b Identico TRUE se $a è uguale a $b, ed essi sono dello stesso tipo. (Solo PHP 4) $a != $b Diversi TRUE se $a è diverso da $b. $a <> $b Diversi TRUE se $a è diverso da $b. $a !== $b Non identici TRUE se $a è diverso da $b, o se essi non sono dello stesso tipo. $a < $b Minore TRUE se $a è strettamente minore di $b. $a > $b Maggiore TRUE se $a è strettamente maggiore di $b. $a <= $b Minore o uguale TRUE se $a è minore o uguale a $b. $a >= $b Maggiore o uguale TRUE se $a è maggiore o uguale a $b.

Un altro operatore condizionale è l'operatore "?:" (o trinario), che opera come in C e molti altri linguaggi.

Questa espressione vale espressione2 se espressione1 è TRUE, e espressione3 se espressione1 è FALSE.

Operatori di controllo errori PHP supporta un operatore di controllo dell'errore: il carattere at (@). Quando prefisso ad una espressione in PHP, qualunque messaggio di errore che potesse essere generato da quella espressione sarà ignorato.

Se la caratteristica track_errors è abilitata, qualsiasi messaggio di errore generato dall'espressione sarà salvato nella variabile globale $php_errormsg. Questa variabile sarà sovrascritta ad ogni errore, così controllatela subito se volete usarla.

Nota: L'operatore @ funziona solo sulle espressioni. Una semplice regola di thumb è: se potete prendere il valore di qualcosa, potete anteporre ad esso l'operatore @. Per esempio, potete anteporre esso a variabili, funzioni e chiamate ad include(), costanti, e così via. non potete anteporre esso a definizioni di funzioni o classi, o strutture condizionali come if e foreach, e così via.

Attenzione: attualmente il prefisso operatore di controllo dell'errore "@" disabiliterà la restituzione di errori per errori critici che interromperanno l'esecuzione dello script. Tra le altre cose, questo significa che se state usando "@" per sopprimere errori da una certa funzione ed essa non è disponibile oppure è stata scritta male, lo script terminerà senza dare indicazioni sul perché.

Operatori di esecuzione PHP supporta un operatore di esecuzione: backticks (``). Notare che quelli non sono apostrofi! PHP cercherà di eseguire il contenuto dei backticks come comando di shell; sarà restituito l'output (i.e., non sarà semplicemente esportato come output; può essere assegnato ad una variabile).

Nota: L'operatore backtick è disabilitato quando è abilitata safe mode oppure quando è disabilitata shell_exec().

Operatori di incremento/decremento Esempio Nome Effetto ++$a Pre-incremento Incrementa $a di una unità, inoltre restituisce $a. $a++ Post-incremento Restituisce $a, inoltre incrementa $a di una unità. --$a Pre-decremento Decrementa $a di una unità, inoltre restituisce $a. $a-- Post-decremento Restituisce $a, inoltre decrementa $a di una unità.

Page 15: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

11 PHP

Operatori logici Esempio Nome Risultato $a and $b And TRUE se entrambi $a e $b sono TRUE. $a or $b Or TRUE se uno tra $a o $b è TRUE. $a xor $b Xor TRUE se uno tra $a o $b è TRUE, ma non entrambi. ! $a Not TRUE se $a non è TRUE. $a && $b And TRUE se entrambi $a e $b sono TRUE. $a || $b Or TRUE se uno tra $a o $b è TRUE.

La ragione per le due differenti variazioni degli operatori "and" e "or" è che essi operano con differenti precedenze.

Operatori di stringa Ci sono due operatori di stringa. Il primo è l'operatore di concatenazione ('.'), che restituisce la concatenazione dei suoi argomenti a destra e a sinistra. Il secondo è l'operatore di assegnazione concatenata ('.='), che aggiunge alla fine dell'argomento sul lato destro l'argomento sul lato sinistro.

Strutture di controllo

if Il costrutto if permette l'esecuzione condizionata di frammenti di codice. La struttura di controllo if di PHP è simile a quella del linguaggio C:

if (espressione) istruzione Espressione restituirà il suo valore booleano. Se espressione vale TRUE, PHP eseguirà istruzione, e se essa vale FALSE la ignorerà.

Spesso sarà necessario eseguire più di una istruzione condizionale. Naturalmente non è necessario, utilizzare una singola clausola if per ciascuna istruzione. Si possono raggruppare diverse istruzioni in un singolo gruppo di istruzioni. Per esempio, il codice che segue visualizzerà a è maggiore di b se $a è maggiore di $b, e successivamente assegnerà il valore della variabile $a alla variabile $b:

Si possono annidare indefinitamente istruzioni if, la qual cosa fornisce piena flessibilità per l'esecuzione di istruzioni condizionali in diversi punti del programma.

else Spesso è necessario eseguire un'istruzione se una proposizione è vera e un'altra istruzione se la proposizione è falsa. Per questo si usa la clausola else.

else estende il costrutto if aggiungendo la possibilità di eseguire un'istruzione se l'espressione nel ramo if è FALSE.

Il ramo else viene eseguito solo se l'espressione nel ramo if è FALSE, e, nel caso ci fossero delle clausole elseif, solamente se le espressioni in esse contenute fossero anch'esse FALSE (vedere elseif).

elseif (oppure else if) elseif, come è facile intuire, è una combinazione di if ed else. Analogamente ad else, estende if aggiungendo la possibilità di eseguire un'altra istruzione nel caso in cui l'espressione contenuta nel ramo if sia FALSE. Però, a differenza di else, si eseguirà l'istruzione alternativa solamente se l'espressione contenuta nel ramo elseif sarà TRUE.

Nel medesimo blocco if possono essere presenti più di una clausola elseif. Verrà eseguita l'istruzione del primo ramo elseif la cui espressione sia TRUE.

L'istruzione di un ramo elseif verrà eseguita solo se l'espressione del ramo if e le espressioni dei rami elseif precedenti sono FALSE, e se l'espressione del ramo elseif è TRUE.

Sintassi alternativa per le strutture di controllo PHP offre una sintassi alternativa per alcune delle sue strutture di controllo; vale a dire, if, while, for, foreach e switch.

Fondamentalmente la sintassi alternativa consiste nel sostituire la prima parentesi graffa con il carattere "duepunti" (:) e la seconda parentesi graffa con

endif;, endwhile;, endfor;, endforeach;, oppure endswitch;, rispettivamente.

La sintassi alternativa si applica anche ad else ed elseif.

Page 16: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

12 PHP

while Il ciclo while è la forma di ciclo più semplice tra quelle possibili in PHP. Si comporta come la sua controparte nel linguaggio C. La forma di base di un ciclo while è la seguente:

while (espressione) istruzione Il significato di un ciclo while è semplice. Istruisce l'interprete PHP perchè esegua l'istruzione (o le istruzioni) in esso racchiuse, ripetutamente, fintanto che l'espressione contenuta nella clausola while ha valore TRUE. Il valore dell'espressione viene verificato ogni volta che il ciclo si ripete (iterazione), così che anche se il valore dell'espressione cambia durante l'esecuzione dell'istruzione, il ciclo non termina fino all'iterazione successiva. Ovviamente, se l'espressione nella clausola while ha valore FALSE dall'inizio, l'istruzione racchiusa nel blocco non verrà eseguita nemmeno una volta. Come nel caso della struttura di controllo if, si possono raggruppare più istruzioni nello medesimo ciclo while racchiudendo le istruzioni in parentesi graffa, oppure utilizzando la sintassi alternativa:

while (espressione): istruzione ... endwhile;

do..while Il ciclo do..while è simile al ciclo while, con l'unica differenza che il valore dell'espressione viene controllato alla fine di ogni iterazione anzichè all'inizio. La differenza più importante rispetto a while è che la prima iterazione di un blocco do..while verrà sempre eseguita (il valore dell'espressione viene controllato alla fine del ciclo), mentre non sarà necessariamente eseguito in un ciclo while (il valore dell'espressione viene controllato all'inizio del ciclo, e se tale valore è FALSE dall'inizio, l'esecuzione del ciclo termina immediatamente).

È ammessa una sola sintassi per il ciclo do..while.

for Il ciclo for è il ciclo più complesso tra quelli disponibili in PHP. Si comporta come la sua controparte nel linguaggio C. La sintassi di un clico for è:

for (espressione1; espressione2; espressione3) istruzione Il valore della prima espressione (espressione1) viene verificato (eseguito) una sola volta incondizionatamente all'inizio del ciclo.

Ad ogni iterazione, si controlla il valore di espressione2. Se è TRUE, il ciclo prosegue e viene eseguita l'istruzione (o le istruzioni) contenuta nel blocco; se è FALSE, l'esecuzione del ciclo termina.

Al termine di ogni iterazione, si verifica (si esegue) il valore di espressione3.

Le due espressioni possono anche non essere presenti. Se non esiste espressione2 significa che il ciclo deve essere eseguito indefinitamente (PHP considera implicitamente che il suo valore è TRUE, come in C). Questa possibilità in fondo non è utile come può sembrare perchè obbliga a terminare il ciclo utilizzando l'istruzione break invece di utilizzare le espressioni booleane del ciclo for .

PHP offre una sintassi alternativa (con i "punto e virgola") per i cicli for.

for (espressione1; espressione2; espressione3): istruzione; ...; endfor;

foreach PHP 4 (non PHP 3) permette l'uso della struttura di controllo foreach, alla stessa maniera del linguaggio Perl e altri. Ciò semplicemente fornisce una facile metodo per attraversare un array. Esistono due possibili notazioni sintattiche; la seconda è un'utile estensione della prima:

foreach(array_expression as $value) istruzione foreach(array_expression as $key => $value) istruzione La prima attraversa l'array dato da array_expression. Ad ogni ciclo, si assegna il valore dell'elemento corrente a $value e il puntatore interno avanza di una posizione (in modo tale che al ciclo successivo l'elemento corrente sarà il successivo elemento dell'array).

La seconda esegue lo stesso ciclo con la differenza che il valore dell'indice corrente viene assegnato ad ogni ciclo, alla variabile $key.

Nota: All'inizio dell'esecuzione di un ciclo foreach il puntatore interno viene automaticamente posizionato nella prima posizione. Questo significa che non è necessario utilizzare la funzione reset() prima di un ciclo foreach.

Nota: È importante notare che foreach opera su una copia dell'array, non sull'array stesso, pertanto il puntatore dell'array originale non viene modificato come accade utilizzando la funzione each() e le modifiche agli elementi dell'array non appaiono nell'array originale.

Nota: foreach non offre la possibilità di annullare la generazione di messaggi d'errore utilizzando il carattere '@'.

break break termina l'esecuzione di una struttura for, foreach while, do..while o switch.

break accetta un argomento opzionale che definisce, nel caso di cicli annidati, il livello del ciclo che è da interrompere.

Page 17: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

13 PHP

continue continue si utilizza per interrompere l'esecuzione del ciclo corrente e continuare con l'esecuzione all'inizio del ciclo successivo.

continue accetta un argomento numerico opzionale che definisce, nel caso di cicli annidati, il numero di cicli da interrompere e da cui iniziare l'esecuzione dell'iterazione successiva.

switch switch è simile a una serie di if sulla stessa espressione. In molti casi può essere necessario confrontare una variabile (o espressione) con differenti valori ed eseguire un differente blocco di istruzioni a seconda del valore di detta variabile. Questo è esattamente quello che fa la struttura di controllo switch. La sintassi è uguale a quella del C.

È importante comprendere esattamente come viene eseguita la clausola switch per evitare errori. Un'istruzione switch esegue linea dopo linea le istruzioni in essa contenuta. All'inizio non viene eseguito alcun codice. Solamente quando incontra una clausola case il cui valore è uguale al valore della viariabile, PHP inizia ad eseguire le istruzioni contenute nel blocco case. PHP continua l'esecuzione delle istruzioni fino alla termine del blocco switch, o quando incontra un'istruzione break. Se non esiste alcuna istruzione break al termine di un blocco case PHP continuerà l'esecuzione delle istruzioni del blocco case successivo.

In un'istruzione switch, la condizione in parentesi viene valutata una sola volta e il risultato viene confrontato con ciascun ramo case. Utilizzando elseif, la condizione viene valutata una seconda volta. Se tale condizione è più complessa di un semplice confronto e/o è in un ciclo piuttosto pesante, l'uso di switch dovrebbe garantire un minor tempo di esecuzione.

Un blocco case può anche non contenere istruzioni, nel qual caso il controllo passa semplicemente al successivo blocco case.

Un blocco case speciale è il il blocco case di default. Uguaglia tutte le condizioni non uguagliate nei blocchi case precedenti e dev'essere l'ultimo blocco case. Per esempio:

L'espressione in un ramo case può essere qualsiasi espressione il cui valore sarà di tipo intero, decimale, numerico e stringa. Array e oggetti (objects) non sono ammessi a meno che non siano dereferenziati a un tipo di dato semplice tra quelli precedentemente elencati.

Come per altre strutture di controllo è possibile utilizzare una sintassi alternativa.

return Se viene chiamato all'interno di una funzione, l'istruzione return() termina immediatamente l'esecuzione della funzione corrente, e restituisce il suo argomento come valore della funzione chiamata. return() terminerà anche l'esecuzione di un'istruzione eval() o di un file di script.

Se viene chiamato in uno scope globale, allora verrà terrminata l'esecuzione del file di script corrente. Nel caso in cui il file di script corrente sia un file chiamato da include() o require(), il controllo viene passato al file chiamante. Ciononostante, se il file di script corrente è un file chiamato da include(), allora il valore dato da return() verrà restituito come valore della chiamata include(). Se viene chiamato return() all'interno del file di script principale, allora l'esecuzione dello script terminerà. Se il file di script corrente è stato nominato da auto_prepend_file o auto_append_file con le opzioni di configurazione nel file di configurazione, allora l'esecuzione di quello script termina.

Nota: Notate che poichè return() è un costrutto di linguaggio e non una funzione, le parentesi che circondano i suoi argomenti non sono richieste --infatti, è più comune evitarle che usarle, nonostante ciò non c'è motivo di preferire un modo o l'altro.

require() L'istruzione require() include e valuta il file specifico.

require() include e valuta uno specifico file. Informazioni dettagliate su come funziona quest'inclusione sono descritte nella documentazione di include().

require() e include() sono identiche in ogni senso eccetto per come esse trattano gli errori. include() produce un Warning mentre require() restituisce un Fatal Error. In altre parole, non esitate ad usare require() se volete che un file mancante fermi l'esecuzione della pagina. include() non si comporta in questo modo, lo script continuerà nonostante tutto. Assicuratevi di avere un appropriato include_path impostato a dovere.

Nota: Prima di PHP 4.0.2, si applica la seguente logica: require() tenterà sempre di leggere il file chiamato, anche se la riga su cui si trova non verrà mai eseguita. L'istruzione condizionale non avrà effetto su require(). Comunque, se la riga su cui si verifica require() non viene eseguita, non sarà eseguito nemmeno il codice del file incluso. Similmente, le strutture cicliche non avranno effetto sul comportamento di require(). Sebbene il codice contenuto nel file incluso è ancora soggetto a ciclo, require() stesso si verifica solo una volta.

include() L'istruzione include() include e valuta il file specificato.

La documentazione seguente si applica anche a require(). I due costrutti sono identici in ogni aspetto eccetto per come essi trattano gli errori. include() produce un Warning mentre require() restituisce un Fatal Error. In altre parole, usate

Page 18: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

14 PHP

require() se volete che un file mancante fermi l'esecuzione della pagina. include() non si comporta in questo modo, lo script continuerà nonostante tutto. Assicuratevi di avere un appropriato include_path impostato a dovere.

Quando un file viene incluso, il codice che esso contiene eredita lo scope delle variabili della riga in cui si verifica l'inclusione. Qualsiasi variabile disponibile in quella riga nella chiamata al file sarà disponibile all'interno del file chiamato, da quel punto in avanti.

Se l'inclusione si verifica dentro una funzione all'interno del file chiamato, allora tutto il codice contenuto nel file chiamato si comporterà come se esso sia stato definito all'interno di una funzione. Così, esso seguirà lo scope delle variabili di quella funzione.

Quando un file viene incluso, il parsing esce dalla modalità PHP e entra in modalità HTML all'inizio del file incluso, e riprende alla fine. Per questa ragione, qualunque codice all'interno del file incluso che dovrebbe essere eseguito come codice PHP deve essere incluso all'interno dei tag PHP validi di apertura e chiusura.

Se "URL fopen wrappers" nel PHP sono abilitati (come nella configurazione di default), potete specificare il file da includere usando un URL (via HTTP) invece che un percorso locale. Se il server chiamato interpreta il file incluso come codice PHP, le variabili possono essere passate al file incluso usando una stringa di richiesta URL come con l'utilizzo di HTTP GET. Non è proprio parlare della stessa cosa includere il file e averlo ereditato dallo scope di variabili del file chiamante; lo script è stato attualmente eseguito su un server remoto e il risultato è poi stato incluso nello script locale.

Poichè include() e require() sono speciali costrutti di linguaggio, dovete includerli all'interno di blocchi di istruzioni se si trovano in un blocco condizionale.

require_once() L'istruzione require_once() include e valuta il file specificato durante l'esecuzione dello script. È un comportamento simile all'istruzione require(), con la sola differenza che se il codice di un file è stato già incluso, esso non sarà incluso nuovamente. Vedere la documentazione di require() per maggiori informazioni su come funziona quest'istruzione.

require_once() dovrebbe essere usato nei casi dove lo stesso file potrebbe essere incluso e valutato più di una volta durante una particolare esecuzione di uno script, e volete essere sicuri che esso sia incluso esattamente una volta per evitare problemi con la ridefinizione di funzioni, riassegnazione di valori a variabili, etc.

include_once() L'istruzione include_once() include e valuta il file specificato durante l'esecuzione dello script. È un comportamento simile all'istruzione include(), con la sola differenza che se il codice di un file è stato già incluso, esso non sarà incluso nuovamente. Come suggerisce il nome, esso sarà incluso solo una volta.

include_once() dovrebbe essere usato nei casi dove lo stesso file potrebbe essere incluso e valutato più di una volta durante una particolare esecuzione di uno script, e volete essere sicuri che esso sia incluso esattamente una volta per evitare problemi con la ridefinizione di funzioni, riassegnazione di valori a variabili, etc.

Funzioni

Funzioni definite dall’utente Una funzione può essere definita usando la seguente sintassi:

function foo ($arg_1, $arg_2, ..., $arg_n) { echo "Funzione di esempio.\n"; return $retval; } All'interno di una funzione può apparire qualunque codice PHP valido, persino altre funzioni e definizioni di classe.

In PHP 3, le funzioni devono essere definite prima di essere referenziate. Non esiste nessun requisito in PHP 4.

PHP non supporta l'overloading di funzioni, non è possibile indefinire o ridefinire funzioni precedentemente dichiarate.

PHP 3 non supporta un numero variabile di argomenti per le funzioni, sebbene siano supportati gli argomenti di default. PHP 4 li supporta entrambi.

Argomenti delle funzioni L'informazione può essere passata alle funzioni tramite la lista degli argomenti, che sono liste di variabili e/o costanti delimitati dalla virgola.

PHP supporta il passaggio di argomenti per valore (comportamento di default), il passaggio per riferimento, e i valori di default degli argomenti. Le liste di argomenti di lunghezza varabile sono supportate solo in PHP 4 e successivi.

Page 19: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

15 PHP

Costruire argomenti passati per riferimento Di default, gli argomenti della funzione sono passati per valore (così se cambiate il valore dell'argomento all'interno della funzione , esso non cambierà fuori della funzione). Se volete permettere ad una funzione di modificare i suoi argomenti, dovete passarli per riferimento.

Se volete che una argomento sia passato sempre per riferimento ad una funzione, dovete anteporre un ampersand (&) al nome dell'argomento nella definizione della funzione.

Liste di argomenti a lunghezza variabile PHP 4 ha il supporto per le liste di argomenti a lunghezza variabile nelle funzioni definite dall'utente. Ciò è realmente abbastanza semplice, usando le funzioni func_num_args(), func_get_arg(), e func_get_args().

Non è richiesta una speciale sintassi, e le liste di argomenti possono ancora essere provviste esplicitamente con le definizioni di funzioni e si comporteranno normalmente.

Valori restituiti I valori vengono restituiti usando l'istruzione opzionale return. Può essere restituito qualsiasi tipo, incluse liste ed oggetti. Ciò provoca l'interruzione dell'esecuzione della funzione immediatamente e la restituzione del controllo alla linea da cui è stata chiamata.

Non possono essere restituiti valori multipli da una funzione, ma risultati simili possono essere ottenuti restituendo una lista.

Per restituire un riferimento da una funzione, è necessario usare l'operatore di passaggio per riferimento & in entrambe le dichiarazioni di funzioni e quando viene assegnato il valore restituito ad una variabile:

Funzioni di Mail La funzione mail() permette di inviare messaggi di posta elettronica.

mail

Invio mail bool mail ( string a, string oggetto, string messaggio [, string header_addizionali [, string parametri_addizionali]]) mail() invia automaticamente il messaggio specificato in messaggio al destinatario specificato in a. Destinatari multipli possono essere specificati mettendo una virgola tra ogni indirizzo in a. Email con allegati e tipi speciali di contenuto possono essere spedite usando questa funzione. Questo è possibile tramite la codifica MIME.

mail() restituisce TRUE se la mail è stata accettata per la spedizione con successo, altrimenti restituisce FALSE.

Attenzione: L'implementazione Windows della funzione mail() differisce sotto molti aspetti dall'implementazione Unix. Primo, non usa una un programma in locale per comporre i messaggi, ma opera soltanto direttamente sui socket, il che significa che deve essere presente in ascolto un MTA su un socket di rete (che può essere su localhost o su una macchina remota). Secondo, gli header custom quali From:, Cc:, Bcc: e Date: non vengono interpretati subito dal MTA, ma ne viene fatto prima il parsing da parte di PHP. PHP < 4.3 supportava solo gli header Cc: (ed era case-sensitive). PHP >= 4.3 supporta tutti gli header e non è più case-sensitive.

Se viene passata come parametro una quarta stringa, questa stringa viene inserita alla fine dell'intestazione (header). Ciò viene tipicamente usato per aggiungere intestazioni supplementari. Intestazioni multiple supplementari sono separate da un carattere di "a capo" (sia newline che carriage return).

Nota: È necessario usare \r\n per separare le intestazioni, alcuni mail transfer agent sotto Unix potrebbero funzionare anche solo con un singolo newline (\n).

Con il parametro parametri_addizionali è possibile impostare un parametro addizionale a linea di comando per il programma configurato per inviare mail usando sendmail_path. Per esempio si può impostare il corretto valore per envelope sender di sendmail. Potrebbe essere necessario aggiungere l'utente che ha in esecuzione il server web alla configurazione di sendmail per prevenire l'aggiunta dell'intestazione 'X-Warning' quando si imposta envelope sender in questo modo.

È possibile costruire messaggi complessi utilizzando la tecnica di concatenazione delle stringhe.

Nota: Assicurarsi di non avere nessun carattere di newline nei parametri a o oggetto, o la mail non verrà spedita correttamente.

Nota: Il parametro a non può essere un indirizzo nella forma "Qualcosa <[email protected]>". Il comando di mail non sarebbe in grado di effettuare correttamente il parsing mentre dialoga con il MTA.

Page 20: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

16 PHP

Funzioni Matematiche

abs

Valore assoluto mixed abs ( mixed numero) Restituisce il valore assoluto di un numero. Se l'argomento della funzione è di tipo float, il valore restituito è float, altrimenti restituisce un integer (perché float di solito ha un range di valori più grande di integer).

acos

Arco coseno float acos ( float arg) Restituisce l'arco coseno di arg in radianti.

asin

Arco seno float asin ( float arg) Restituisce l'arco seno di arg in radianti.

atan

Arco tangente float atan ( float arg) Restituisce l'arco tangente di arg in radianti.

base_convert

Converte un numero fra basi arbitrarie string base_convert ( string numero, int base_di_partenza, int base_di_arrivo) Restituisce una stringa contenente numero rappresentata in base base_di_arrivo. La base in cui numero è dato è specificata da base_di_partenza. Entrambe base_di_partenza e base_di_arrivo devono essere comprese fra 2 e 36, inclusi. Cifre in numeri con una base maggiore di 10 saranno rappresentati con le lettere a-z, con a significante 10, b significante 11 e z significante 35.

bindec

Da binario a decimale int bindec ( string stringa_binaria) Restituisce il decimale equivalente al numero binario rappresentato dall'argomento stringa_binaria.

bindec() converte un binario in integer. Il più grande numero che può essere convertito è 31 volte la cifra 1 oppure 2147483647 espresso in formato decimale.

ceil

Arroronda le frazioni all'intero superiore float ceil ( float numero) Restituisce il primo intero più grande di numero, se necessario. Il valore restituito da ceil() è ancora di tipo float, poiché la gamma di valori del tipo float è solitamente più grande di quella del tipo int.

cos

Coseno float cos ( float arg) Restituisce il coseno di arg in radianti.

Page 21: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

17 PHP

decbin

Da decimale a binario string decbin ( int numero) Restituisce una stringa contenente una rappresentazione binaria di un dato argomento numero. Il più grande numero che può essere convertito è 4294967295 in decimale, risultante in una stringa composta da 32 volte la cifra 1.

dechex

Da decimale a esadecimale string dechex ( int numero) Restituisce una stringa contenente una rappresentazione esadecimale di un dato argomento numero. Il più grande numero che puù essere convertito è 2147483647 in decimale risultante in "7fffffff".

decoct

Da decimale a ottale string decoct ( int numero) Restituisce una stringa contenente una rappresentazione in ottale di un dato argomento numero. Il più grande numero che può essere convertito è 2147483647 in decimale risultante in "17777777777".

deg2rad

Converte il numero dato in gradi nell'equivalente espresso in radianti double deg2rad ( double numero) Questa funzione converte numero da gradi al valore equivalente espresso in radianti.

exp

e elevato alla potenza di ... float exp ( float arg) Restituisce e elevato alla potenza di arg.

floor

Arrotonda le frazioni all'intero inferiore float floor ( float numero) Restituisce il primo intero più piccolo di numero, se necessario. Il valore restituito da floor() è ancora di tipo float, poiché la gamma di valori del tipo float è solitamente più grande di quella del tipo int.

fmod

Returns the floating point remainder (modulo) of the division of the arguments float fmod ( float x, float y) Returns the floating point remainder of dividing the dividend (x) by the divisor (y). The reminder (r) is defined as: x = i * y + r, for some integer i. If y is non-zero, r has the same sign as x and a magnitude less than the magnitude of y.

getrandmax

Mostra il più grande numero casuale disponibile int getrandmax ( void) Restituisce il valore massimo che può essere restituito da una chiamata alla funzione rand().

Page 22: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

18 PHP

hexdec

Da esadecimale a decimale int hexdec ( string stringa_esadecimale) Restituisce l'equivalente decimale di un numero esadecimale rappresentato dall'argomento stringa_esadecimale. hexdec() converte una stringa esadecimale in un numero decimale. Il più grande numero che può essere convertito è 7fffffff o 2147483647 espresso in decimale.

hexdec() sostituisce ogni carattere non esadecimale che incontra con 0. In questo modo, tutti gli zeri a sinistra sono ignorati, ma gli zeri a destra sono valutati.

is_finite

bool is_finite ( float val) Restituisce TRUE se val è un numero finito valido all'interno del range dei float, come definito da PHP su questa piattaforma.

is_infinite

bool is_infinite ( float val) Restituisce TRUE se val è infinito (positivo o negativo), come il risultato di log(0) o ogni altro valore troppo grande per essere contenuto nel range dei float di una determinata piattaforma.

is_nan

bool is_nan ( float val) Restituisce TRUE se val 'non è un numero', come il risultato di acos(1.01).

lcg_value

Generatore combinato lineare congruenziale float lcg_value ( void) lcg_value() restituisce uno pseudo numero casuale nell'intervallo (0, 1). La funzione combina due GC con periodo di 2^31 - 85 e 2^31 - 249. Il periodo di questa funzione è uguale al prodotto dei due primi.

log10

Logaritmo base-10 float log10 ( float arg) Restituisce il logaritmo in base-10 di arg.

log

float log ( float arg) Restituisce il logaritmo naturale di arg.

max

Trova il valore massimo mixed max ( mixed arg1, mixed arg2, mixed argn) max() restituisce il numericamente più grande dei valori dati come parametro.

Se il primo parametro è un array, max() restituisce il massimo dei valori di tale array. Se il primo parametro è un integer, string o double, si ha bisogno almeno di due parametri e max() restituisce il maggiore di tali valori. Si può confrontare un numero illimitato di valori.

Se uno o più valori sono float, tutti i valori saranno considerati come float, e verrà restituito un float. Se nessuno dei valori è double, tutti verranno considerati come integer, e verrà restituito un integer.

Page 23: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

19 PHP

min

Trova il valore minimo mixed min ( mixed arg1, mixed arg2, mixed argn) number min ( array numeri) min() restituisce il numericamente più piccolo dei valori dati come parametro.

Nella prima variante, si ha bisogno di almeno due parametri e min() restituisce il minimo fra i valori. Si può confrontare un numero illimitato di valori.

Nella seconda variante, min() restituisce il più piccolo valore in numeri.

Se uno o più valori sono float, tutti i valori saranno considerati come float, e verrà restituito un float. Se nessuno dei valori è float, tutti verranno considerati come integer, e verrà restituito un integer.

octdec

Da ottale a decimale int octdec ( string stringa_ottale) Restituisce l'equivalente decimale del numero ottale rappresentato dall'argomento stringa_ottale. OctDec converte una stringa ottale in un numero decimale. Il più grande numero che può essere convertito è 17777777777 o 2147483647 in decimale.

pi

Restituisce il valore di pi double pi ( void) Restituisce una appossimazione di pi. Il valore restituito è un float e ha precisione secondo la direttiva precision del file php.ini, che ha come valore predefinito 14. Inoltre, si può usare la costante M_PI che permette di ottenere risultati identici all'uso di pi().

pow

Espressione esponenziale float pow ( float base, float esp) Restituisce base elevato alla potenza di esp. Se possibile, questa funzione restituisce un integer. Se la potenza non può essere computata, viene generato un errore, e pow() restituirà FALSE.

rad2deg

Converte un numero in radianti nell'equivalente numero in gradi double rad2deg ( double numero) Questa funzione converte numero da radianti a gradi.

rand

Genera un valore casuale int rand ( [int min, int max]) Se chiamata senza i parametri opzionali min, max, rand() restituisce un valore pseudo casuale compreso fra 0 e RAND_MAX. Se ad esempio si desidera un numero casuale compreso fra 5 e 15 (inclusi) usare rand (5, 15).

Ricordarsi di inizializzare il generatore di numeri casuali usando srand().

Nota: Nelle versioni precedenti la 3.0.7 il significato di max era range. Per ottenere lo stesso risultato in queste vecchie versioni un breve esempio dovrebbe essere il seguente: rand (5, 11), si otterrà un numero casuale compreso fra 5 e 15.

round

Arrotonda un numero non intero double round ( double val [, int precisione]) Restituisce il valore arrotondato di val con la precisione specificata (numero di cifre dopo il punto decimale). precision può anche essere negativa o zero (predefinito).

Page 24: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

20 PHP

sin

Seno float sin ( float arg) Restituisce il seno di arg in radianti.

sqrt

Radice quadrata float sqrt ( float arg) Restituisce la radice quadrata di arg.

srand

Inizializza il generatore di numeri casuali void srand ( int seme) Inizializza il generatore di num casuali con seme.

tan

Tangente float tan ( float arg) Restituisce la tangente di arg in radianti.

Funzioni InterBase

ibase_blob_add

Aggiunge dati in un blob creato int ibase_blob_add ( int blob_id, string data)

ibase_blob_cancel

Cancella la creazione di un blob int ibase_blob_cancel ( int blob_id)

ibase_blob_close

Chiude un blob int ibase_blob_close ( int blob_id)

ibase_blob_create

Crea un blob per aggiungerci dei dati int ibase_blob_create ( [int link_identifier])

ibase_blob_echo

Visualizza il contenuto di un blob sul browser int ibase_blob_echo ( string blob_id_str)

Page 25: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

21 PHP

ibase_blob_get

Ottiene len byte di dati dal blob aperto string ibase_blob_get ( int blob_id, int len)

ibase_blob_import

Create un blob, copy il file al suo interno e lo chiude string ibase_blob_import ( [int link_identifier, int file_id])

ibase_blob_info

Restituisce la lunghezza del blob e altre informazioni utlili object ibase_blob_info ( string blob_id_str)

ibase_blob_open

Apre un blob per ricavare parte di dati int ibase_blob_open ( string blob_id)

ibase_close

Chiude una connessione ad un database InterBase int ibase_close ( [int connection_id]) Chiude il collegamento ad un database InterBase che è stato associato con un id di connessione restituito da ibase_connect(). Se l'id di connessione viene omesso, viene considerato l'ultimo collegamento che è stato aperto. La transazione predefinita sul collegamento viene "committed", le altre transazioni vengono "rolled back".

ibase_commit

Esegue il commit di una transazione int ibase_commit ( [int link_identifier, int trans_number]) Esegue il commit della transazione trans_number che è stata creata con ibase_trans().

ibase_connect

Apre una connessione con un database InterBase int ibase_connect ( string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role]]]]]]) Stabilisce una connessione con un server InterBase. Il parametro database deve essere un percorso valido di un file di database sul server dove risiede. Se il server non fosse locale, bisogna aggiungere prima del percorso o 'hostname:' (TCP/IP), o '//hostname/' (NetBEUI) o 'hostname@' (IPX/SPX), in base al protocollo di connessione utilizzato. username e password possono venire specificati anche con le direttive di configurazione del PHP ibase.default_user e ibase.default_password. charset è il set di caratteri predefinito per un database. buffers è il numero di buffer di database da allocare per la cache dal lato server. Se è 0 o viene omesso, il server usa il suo valore predefinito. dialect seleziona il dialetto SQL predefinito per ogni operazione eseguita all'interno di una connessione, e il suo valore predefinito è il più alto supportato dalle librerie del client. Nel caso di una seconda chiamata fatta con ibase_connect() con gli stessi parametri, non verrà creato alcun nuovo collegamento, bensì, l'identificatore del collegamento già aperto verrà restituito. Il collegamento al server verrà chiuso appena termina l'esecuzione dello script, a meno che non venga chiuso prima esplicitamente chiamando ibase_close().

ibase_errmsg

Restituisce messaggi di errore string ibase_errmsg ( void) Restituisce una stringa contenente un messaggio di errore.

Page 26: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

22 PHP

ibase_execute

Esegue una query preparata in precedenza int ibase_execute ( int query [, int bind_args]) Esegue una query preparata da ibase_prepare(). Ciò è molto più efficace che usare ibase_query() se state ripetendo uno stesso tipo di query molte volte cambiando solo alcuni parametri.

ibase_fetch_object

Ottiene un oggetto da un database InterBase object ibase_fetch_object ( int result_id) Elabora una riga come un pseudo-oggetto da un result_id ottenuto o da ibase_query() o da ibase_execute().

Chiamate successive a ibase_fetch_object() restituiscono la successiva riga dai risultati della query o FALSE se non vi sono ulteriori righe.

ibase_fetch_row

Elabora una riga da un database InterBase array ibase_fetch_row ( int result_identifier) Restituisce un array che corrisponde alla riga ottenuta o FALSE se non ci sono righe rimanenti.

ibase_fetch_row() prende una riga di dati dai risultati associati allo specificato result_identifier. La riga viene restituita come un array. Ogni colonna risultante viene immagazzinata in un offset dell'array, l'offset inizia da 0.

Chiamate successive a ibase_fetch_row() restituiscono la successiva riga dai risultati della query o FALSE se non vi sono ulteriori righe.

ibase_field_info

Ottiene informazioni su un campo array ibase_field_info ( int result, int field number) Restituisce un array con informazioni relative a un campo dopo che una query select è stata eseguita. L'array ha la forma name, alias, relation, length e type.

ibase_free_query

Libera la memoria allocata da una query preparata int ibase_free_query ( int query) Libera una query preparata da ibase_prepare().

ibase_free_result

Libera la memoria allocata da un result set int ibase_free_result ( int result_identifier) Libera un result set che è stato creato da ibase_query().

ibase_num_fields

Ottiene il numero di campi in un result set int ibase_num_fields ( int result_id) Restituisce un integer contenente il numero di campi in un result set.

ibase_pconnect

Crea una connessione persistente ad un database Interbase int ibase_connect ( string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role]]]]]]) ibase_pconnect() agisce in modo molto simile a ibase_connect() con due differenze principali. Innanzitutto, durante la connessione, la funzione cercherà prima di trovare un collegamento (persistente) che è già stato aperto con gli stessi parametri. Se viene trovato, il suo identificatore verrà restituito al posto di aprire una nuova connessione. In secondo

Page 27: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

23 PHP

luogo, la connessione al server InterBase non verrà chiusa al termine dell'esecuzione dello script. Invece, il collegamento resterà aperto per un uso futuro (ibase_close() non chiuderà i collegamenti stabiliti da ibase_pconnect()). Questo tipo di collegamento è perciò chiamato 'persistente'.

ibase_prepare

Prepara una query per un successivo binding dei segnaposto dei parametri ed esecuzione int ibase_prepare ( [int link_identifier, string query]) Prepara una query per un successivo binding dei segnaposto dei parametri ed esecuzione (tramite ibase_execute()).

ibase_query

Esegue una query su di un database InterBase int ibase_query ( [int link_identifier, string query [, int bind_args]]) Esegue una query su di un database InterBase. Se la query non ha successo, restituisce FALSE. Se ha successo e vi sono righe di risultato (come si ha ad esempio con le query SELECT), restituisce un identificatore di risorsa. Se la query ha avuto successo, ma non ci sono risultati, restituisce TRUE. Restutuisce FALSE se la query fallisce.

ibase_rollback

Esegue il roll back di una transazione int ibase_rollback ( [int link_identifier, int trans_number])

ibase_timefmt

Imposta il formato delle colonne timestamp, date e time restituite dalle query int ibase_timefmt ( string format [, int columntype]) Imposta il formato delle colonne di tipo timestamp, date o time restituite dalle query.

ibase_trans

Inizia una transazione int ibase_trans ( [int trans_args [, int link_identifier]])

Funzioni MySQL

mysql_affected_rows

Ottiene il numero di righe coinvolte nelle precedenti operazioni MySQL int mysql_affected_rows ( [resource identificativo_connessione]) mysql_affected_rows() restituisce il numero di righe coinvolte nell'ultima query INSERT, UPDATE o DELETE associata a identificativo_connessione. Se l'identificativo di connessione non è specificato, viene considerata l'ultima connessione aperta con mysql_connect().

Nota: Se sono usate le transazioni, è necessario richiamare mysql_affected_rows() dopo le query INSERT, UPDATE, o DELETE e non dopo il commit.

Se l'ultima query era una query DELETE senza clausola WHERE, tuti i record saranno cancellati dalla tabella ma questa funzione restituirà zero.

Nota: Usando UPDATE, MySQL non aggiornerà le colonne nelle quali il nuovo valore è uguale al vecchio valore. Questo crea la possibilità che mysql_affected_rows() può non uguagliare realmente il numero di righe corrispondenti ma solo il numero di righe effettivamente coinvolte dalla query.

mysql_affected_rows() non funziona con l'istruzione SELECT ma solo con le istruzioni che modificano i record. Per ricavare il numero di righe restituite da SELECT, usare mysql_num_rows().

Se l'ultima query fallisce, questa funzione restituisce -1.

mysql_change_user

Cambia l'utente della connessione attiva

Page 28: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

24 PHP

int mysql_change_user ( string nome_utente, string password [, string database [, resource identificativo_connessione]]) mysql_change_user() cambia l'utente dell'attuale connessione attiva o della connessione specificata dal parametro opzionale identificativo_connessione. Se un database is specificato, questo sarà il database corrente dopo che l'utente è stato cambiato. Se l'autorizzazione del nuovo utente e password falllisce, l'attuale utente connesso rimane attivo. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

mysql_client_encoding

Restituisce il nome del set di caratteri int mysql_client_encoding ( [resource identificativo_connessione]) mysql_client_encoding() restituisce il nome del set di caratteri predefinito per l'attuale connessione.

mysql_close

Chiude una connessione MySQL bool mysql_close ( [resource identificativo_connessione]) Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

mysql_close() chiude la connessione al server MySQL associata all'identificativo di connessione specificato. Se identificativo_connessione non è specificato, viene usata l'ultima connessione aperta.

L'uso di mysql_close() non è normalmente necessario, dal momento che le connessioni non persistenti sono chiuse automaticamente alla fine dell'esecuzione dello script.

Nota: mysql_close() non chiude le connessioni persistenti create da mysql_pconnect().

mysql_connect

Apre una connessione ad un server MySQL resource mysql_connect ( [string server [, string nome_utente [, string password [, bool nuova_connessione [, int client_flags]]]]]) Restituisce un identificativo di connessione MySQL in caso di successo oppure FALSE in caso di fallimento.

mysql_connect() stabilice una connessione ad un server MySQL. I seguenti valore predefiniti sono assunti per i parametri opzionali mancanti: server = 'localhost:3306', nome_utente = nome dell'utente proprietario del processo server e password = password vuota.

Il parametro server può anche includere un numero di porta. Es. "hostname:porta" o un percorso ad un socket es. ":/percorso/al/socket" per il localhost.

Si può eliminare il messaggio di errore nel caso di fallimento aggiungendo il prefisso @ al un nome della funzione.

Se si fa una seconda chiamata a mysql_connect() con gli stessi argomenti, nessuna nuova connessione sarà stabilita, ma sarà restituito l'identificativo della connessione già aperta. Il paramentro nuova_connessione modifica questo comportamento e fa sì che mysql_connect() apra sempre una nuova connessione, anche se mysql_connect() era stata chiamata prima con gli stessi parametri. il parametro client_flags può essere combinato con le costanti MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE o MYSQL_CLIENT_INTERACTIVE.

La connessione al server sarà chiusa prima della fine dell'esecuzione dello script, a meno che questa non sia precedentemente chiusa esplicitamente richiamando mysql_close().

mysql_create_db

Crea un database MySQL bool mysql_create_db ( string nome_database [, resource identificativo_connessione]) mysql_create_db() tenta di creare un nuovo database nel server associato all'identificativo di conmnessione specificato.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Nota: La funzione mysql_create_db() è sconsigliata. Al suo posto è preferibile usare mysql_query() per inviare un'istruzione SQL CREATE DATABASE.

mysql_data_seek

Muove il puntatore interno del risultato bool mysql_data_seek ( resource identificativo_risultato, int numero_riga)

Page 29: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

25 PHP

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

mysql_data_seek() muove il puntatore di riga interno del risultato MySQL associato all'identificativo specificato per puntare ad un determinato numero di riga. La successiva chiamata a mysql_fetch_row() dovrebbe restituire questa riga.

numero_riga inizia da 0. numero_riga dovrebbe essere un valore nell'intervallo che va da 0 a mysql_num_rows - 1.

Nota: La funzione mysql_data_seek() può essere usata solo insieme a mysql_query(), non con mysql_unbuffered_query().

mysql_db_name

Ottiene dei dati dal risultato string mysql_db_name ( resource risultato, int riga [, mixed campo]) mysql_db_name() accetta come primo paramentro il puntatore al risultato dalla chiamata a mysql_list_dbs(). Il parametro riga è un indice compreso nell'intervallo del risultato.

Se intercorre un errore, viene restituito FALSE. Usare mysql_errno() e mysql_error() per determinare la natura dell'errore.

mysql_drop_db

Elimina (cancella) un database MySQL bool mysql_drop_db ( string nome_database [, resource identificativo_connessione]) Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

mysql_drop_db() tenta di eliminare (cancellare) un intero database dal server associato all'identificativo di connessione specificato.

Nota: La funzione mysql_drop_db() è sconsigliata. Al suo posto è preferibile usare mysql_query() per inviare una istruzione SQL DROP DATABASE.

mysql_errno

Restituisce il valore numerico del messaggio di errore della precedente operazione MySQL int mysql_errno ( [resource identificativo_connessione]) Restituisce il numero di errore dall'ultima funzione MySQL, oppure 0 (zero) se nessun errore è intercorso.

Gli errori ritornano dal database MySQL senza visualizzare i messaggi di avvertimento. Usando invece mysql_errno() si recupera il codice di errore. Notare che questa funzione restituisce solo il codice errore della più recente funzione MySQL eseguita (ad esclusione di mysql_error() e mysql_errno()), quindi se la si vuole usare, assicurarsi di controllare il valore prima di richiamare un'altra funzione MySQL.

Nota: Se l'argomento opzionale è specificato la connessione indicata viene usata per recuperare il codice d'errore. Altrimenti viene usata l'ultima connessione aperta.

mysql_error

Restituisce il testo del messagio di errore della precedente operazione MySQL string mysql_error ( [resource identificativo_connessione]) Restituisce il testo dell'errore dall'ultima funzione MySQL, oppure '' (la stringa vuota) se nessun errore intercorre.

Gli errori ritornano dal database MySQL senza visualizzare i messaggi di avvertimento. Si usa invece mysql_error() per recuperare il testo dell'errore. Notare che questa funzione restituisce solo il testo dell'errore della più recente funzione MySQL eseguita (ad esclusione di mysql_error() e mysql_errno()), quindi se la si vuole usare, assicurarsi di controllare il valore prima di richiamare un'altra funzione MySQL.

Nota: Se l'argomento opzionale è specificato la connessione indicata viene usata per recuperare il codice d'erroe. Altrimenti viene usata l'ultima connessione aperta.

mysql_escape_string

Aggiunge le sequenze di escape in una stringa per l'uso in mysql_query. string mysql_escape_string ( string stringa_senza_escape) Questa funzione aggiunge le sequenze di escape a stringa_senza_escape, in modo che sia sicuro usarla in mysql_query().

Nota: mysql_escape_string() non aggiunge le sequenze di escape a % ed a _.

Page 30: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

26 PHP

Questa funzione è identica a mysql_real_escape_string() eccetto che mysql_real_escape_string() accetta un identificativo di connessione ed aggiunge le sequenze di escape alla stringa in base al set di caratteri corrente. mysql_escape_string() non accetta come argomento un identificativo di connessione e non rispetta le impostazioni del corrente set di caratteri.

mysql_fetch_array

Carica una riga del risultato come un array associativo, un array numerico o entrambe. array mysql_fetch_array ( resource risultato [, int tipo_risultato]) Restituisce un array che corrisponde alla riga caricata o FALSE se non ci sono più righe.

mysql_fetch_array() è una versione estesa di mysql_fetch_row(). Oltre a memorizzare i dati del risultato in array con indice numerico, questa li memorizza anche con indici associativi usando i nomi dei campi come chiavi.

Se due o più colonne del risultato hanno gli stessi nomi di campo, l'ultima colonna avrà la precedenza. Per accedere alle altre colonne con lo stesso nome, si deve usare l'indice numerico della colonna o farne un alias. Per le colonne-alias, non si può accedere al contenuto con il nome della colonna originale (in questo esempio si usa 'campo').

Una cosa importante da notare è che l'uso di mysql_fetch_array() non è significativamente più lento dell'uso di mysql_fetch_row(); questo fornisce un significativo valore aggiunto.

Il secondo argomento opzionale tipo_risultato in mysql_fetch_array() è una costante e può assumere i seguenti valori: MYSQL_ASSOC, MYSQL_NUM e MYSQL_BOTH. Questa caratteristica è stata aggiunta nel PHP 3.0.7. MYSQL_BOTH è il valore predefinito per questo argomento.

Usando MYSQL_BOTH, si ottiene un array con entrambe gli indici (associativo e numerico). Usando MYSQL_ASSOC, si ottengono solo gli indici associativi (stesso funzionamento di mysql_fetch_assoc()), usando MYSQL_NUM, si otengono solo gli indici numerici (stesso funzionamento di mysql_fetch_row()).

mysql_fetch_assoc

Carica una riga del risultato come array associativo array mysql_fetch_assoc ( resource risultato) Restituisce un array associativo che corrisponde alla riga caricata o FALSE se non ci sono più righe.

mysql_fetch_assoc() è equivalente alla chiamata di mysql_fetch_array() con MYSQL_ASSOC come secondo parametro opzionale. Questa restituisce solo un array associativo. Questo è il modo incui mysql_fetch_array() funzionava originalmente. Se è necessario l'indice numerico al posto di quello associativo, usare mysql_fetch_array().

Se due o più colonne del risultato hanno gli stessi nomi di campo, l'ultima colonna avrà la precedenza. Per accedere alle altre colonne con lo stesso nome, si deve accedere al risultato con l'indice numerico usando mysql_fetch_row() oppure aggiunger degli alias.

Una cosa importante da notare è che l'uso di mysql_fetch_assoc() non è significativamente più lento dell'uso di mysql_fetch_row(); questo fornisce un significativo valore aggiunto.

mysql_fetch_field

Ottiene informazioni sulla colonna da un risultato e le restituisce come oggetto object mysql_fetch_field ( resource risultato [, int indice_campo]) Restituisce un oggetto contenente le informazioni di un campo.

mysql_fetch_field() può essere usata al fine di ottenere informazioni circa i campi di un determinato risultato di una query. Se l'indice del campo non è specificato, il successivo campo non ancora recuperato da mysql_fetch_field() viene considerato.

Le proprietà dell'oggetto sono: name - nome della colonna, table - nome della tabella a cui appartiene la colonna, max_length - massima lunghezza della colonna, not_null - 1 se la colonna non può essere NULL, primary_key - 1 se la colonna è una chiave primaria, unique_key - 1 se la colonna è una chiave unica, multiple_key - 1 se la colonna è una chiave non-unica, numeric - 1 se la colonna è numerica, blob - 1 se la colonna è un BLOB, type - il tipo della colonna, unsigned - 1 se la colonna è senza segno, zerofill - 1 se la colonna è completata da zeri

mysql_fetch_lengths

Ottiene la lunghezza di ogni output nel risultato array mysql_fetch_lengths ( resource risultato) Restituisce un array che corrisponde alle lunghezze di ogni campo nell'ultima riga caricata da mysql_fetch_row() oppure FALSE in caso di errore.

mysql_fetch_lengths() memorizza le lunghezze di ogni colonna dell'ultima riga restituita da mysql_fetch_row(), mysql_fetch_array() e mysql_fetch_object() in un array, iniziando con un indice pari a 0.

Page 31: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

27 PHP

mysql_fetch_object

Carica una riga del risultato come un ogetto object mysql_fetch_object ( resource risultato) Restituisce un oggetto con proprietà che corrispondono alla riga caricata oppure FALSE se non ci sono più righe.

mysql_fetch_object() è simile a mysql_fetch_array(), con una differenza - viene restituito un oggetto invece che un array. Indirettamente, questo significa che si ha solo accesso ai dati attraverso i nomi dei campi e non attraverso il loro indice (i mumeri sono nomi di proprietà illeciti).

In termini di velocità, la funzione è identica a mysql_fetch_array() e quasi veloce come mysql_fetch_row() (la differenza è insignificante).

mysql_fetch_row

Ottiene una riga del risultato come un array enumerato array mysql_fetch_row ( resource risultato) Restituisce un array che corrisponde ad una riga caricata oppure FALSE se non ci sono più righe.

mysql_fetch_row() carica una riga di dati dal risultato associato all'identificativo specificato. La riga è restituita com un array. Ogni colonna del risultato è memorizzata in un indice dell'array, partendo dall'indice 0.

La susseguente chiamata a mysql_fetch_row() restituisce la successiva riga nell'intervallo del risultato oppure FALSE se non ci sono più righe.

mysql_field_flags

Ottine i flag associati al campo specificato di un risultato string mysql_field_flags ( resource risultato, int indice_campo) mysql_field_flags() restituisce i flag del campo specificato. I flag sono restituiti come singole parole per flag separate da un singolo spazio, in modo che sia possibile suddividere il valore restituito usando explode().

I seguenti flag sono restituiti, se la versione di MySQL è abbastanza aggiornata da supportarli: "not_null", "primary_key", "unique_key", "multiple_key", "blob", "unsigned", "zerofill", "binary", "enum", "auto_increment", "timestamp".

Per motivi di compatibilità con il passato, anche mysql_fieldflags() può essere usata. Questo comunque è sconsigliato.

mysql_field_len

Restituisce la lunghezza del campo specificato int mysql_field_len ( resource risultato, int indice_campo) mysql_field_len() restituisce la lunghezza del campo specificato.

mysql_field_name

Ottiene il nome del campo specificato in un risultato string mysql_field_name ( resource risultato, int indice_campo) mysql_field_name() restituisce il nome del campo specificato dall'indice. risultato deve essere un identificativo di risultato valido e indice_campo è lo spiazzamento numerico del campo.

Nota: indice_campo inizia da 0. L'indice del terzo campo è in realtà 2, l'indice del quarto campo è 3 e così via.

mysql_field_seek

Imposta il puntatore al risultato ad un determinato indice di campo int mysql_field_seek ( resource risultato, int indice_campo) Esegue il seek ad uno specifico indice di campo. Se la successiva chiamata a mysql_fetch_field() non include un indice di campo, quello specificato in mysql_field_seek() viene restituito.

mysql_field_table

Ottiene il nome della tabella in cui si trova il campo specificato string mysql_field_table ( resource risultato, int indice_campo) Ottiene il nome della tabella in cui si trova il campo specificato.

Page 32: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

28 PHP

mysql_field_type

Ottiene il tipo del campo specificato in un risultato string mysql_field_type ( resource risultato, int indice_campo) mysql_field_type() è simile alla funzione mysql_field_name(). Gli argomenti sono identici, ma viene restituito il tipo del campo. Il tipo del campo sarà uno dei seguenti: "int", "real", "string", "blob" ed altri come dettagliati nella Documentazione di MySQL.

mysql_free_result

Libera la memoria occupata dal risultato bool mysql_free_result ( resource risultato) mysql_free_result() libera tutta la memoria associata all'identificativo del risultato risultato.

mysql_free_result() deve essere richiamata solo se si è preoccupati sulla quantità di memoria usata dalle query che restituiscono dei grandi risultati. Tutta la memoria associata al risultato è automaticamente liberata al termine dell'esecuzione dello script.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

mysql_get_client_info

Ottiene informazioni sul client MySQL string mysql_get_client_info ( void) mysql_get_client_info() restituisce una stringa che rappresenta la versione della libraria client.

mysql_get_host_info

Ottiene le informazioni sull'host MySQL string mysql_get_host_info ( [resource identificativo_connessione]) mysql_get_host_info() restituisce una stringa che descrive il tipo di connessione in uso per identificativo_connessione, includendo il nome dell'host del server. Se identificativo_connessione è omesso, sarà usata l'ultima connessione aperta.

mysql_get_proto_info

Ottiene le informazion sul protocollo MySQL int mysql_get_proto_info ( [resource identificativo_connessione]) mysql_get_proto_info() restituisce la versione del protocollo usata dalla connessione identificativo_connessione. Se identificativo_connessione è omesso, sarà usata l'ultima connessione aperta.

mysql_get_server_info

Ottiene le informazioni sul server MySQL string mysql_get_server_info ( [resource identificativo_connessione]) mysql_get_server_info() restituisce la versione del server usato dalla connessione identificativo_connessione. Se identificativo_connessione è omesso, sarà usata l'ultima connessione aperta.

mysql_info

Ottiene le informazioni relative alla query più recente. string mysql_info ( [resource identificativo_connessione]) mysql_info() restituisce informazioni dettagliate relative all'ultima query usando lo specifico identificativo_connessione. Se identificativo_connessione non è specificato, viene considerata l'ultima connessione aperta.

mysql_info() restituisce una stringa per tutte le istruzioni elencate di seguito. Per tutte le altre restituisce FALSE. Il formato della stringa dipende dall'istruzione data.

Nota: mysql_info() restituisce un valore non FALSE per le istruzioni INSERT ... VALUES solo se nell'istruzione sono specificate liste di valori multipli.

Page 33: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

29 PHP

mysql_insert_id

Ottiene l'identificativo generato dalla precedente operazione INSERT int mysql_insert_id ( [resource identificativo_connessione]) mysql_insert_id() restituisce l'identificativo generato per una colonna AUTO_INCREMENT dal precedente query INSERT usando lo specifico identificativo_connessione. Se identificativo_connessione non è specificato, viene considerata l'ultima connessione aperta.

mysql_insert_id() restituisce 0 se la precedente query non ha generato un valore AUTO_INCREMENT. Se è necessario salvare il valore per usarlo in seguito, assicurarsi di richiamare mysql_insert_id() immediatamente dopo la query che ha generato il valore.

Nota: Il valore della funzione SQL LAST_INSERT_ID() di MySQL contiene sempre il più recente valore AUTO_INCREMENT generato e non è azzerato dalle query.

Attenzione: mysql_insert_id() converte il tipo restituito dalla funzione nativa dell'API C di MySQL mysql_insert_id() al tipo long (chiamata int nel PHP). Se la colonna AUTO_INCREMENT è del tipo BIGINT, il valore restituito da mysql_insert_id() sarà inesatto. In questo caso si usi la funzione SQL di MySQL LAST_INSERT_ID() in una query SQL.

mysql_list_dbs

Elenca i database disponibili in un server MySQL resource mysql_list_dbs ( [resource identificativo_connessione]) mysql_list_dbs() restituirà un risultato puntatore contenete i database resi disponibili dal demone mysql. Usare la funzione mysql_tablename() per esplorare questo risultato puntatore o qualsiasi funzione per i risultati delle tabelle, come mysql_fetch_array().

mysql_list_fields

Elenca i campi di un risultato MySQL resource mysql_list_fields ( string nome_database, string nome_tabella [, resource identificativo_connessione])

mysql_list_fields() recupera le informazioni relative ad una data tabella. Gli argomenti sono il nome del database ed il nome della tabella. Viene restituito un risultato puntatore che può essere usato con mysql_field_flags(), mysql_field_len(), mysql_field_name() e mysql_field_type().

mysql_list_processes

Elenca i processi MySQL resource mysql_list_processes ( [resource identificativo_connessione]) mysql_list_processes() restituisce un risultato puntatore che descrive i thread attuali del server.

mysql_list_tables

Elenca le tabelle in un database MySQL resource mysql_list_tables ( string database [, resource identificativoi_connessione]) mysql_list_tables() accetta un nome di database e restituisce un risultato puntatore in modo molto simile alla funzione mysql_query(). Usare la funzione mysql_tablename() per esplorare questo risultato puntatore o qualsiasi funzione per i risultati delle tabelle, come mysql_fetch_array().

Il parametro database è il nome del database da cui recuperare la lista di tabelle. in caso di errore, mysql_list_tables() restituisce FALSE.

mysql_num_fields

Ottiene il numero di campi nel risultato int mysql_num_fields ( resource risultato) mysql_num_fields() restituisce il numero di campi in un risultato.

Page 34: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

30 PHP

mysql_num_rows

Ottiene il numero di righe in un risultato int mysql_num_rows ( resource risultato) mysql_num_rows() restituisce il numero di righe in un risultato. Questo comando è valido solo per le istruzioni SELECT. Per recuperare il numero di righe coinvolte dalle query INSERT, UPDATE o DELETE, usare mysql_affected_rows().

Nota: Se si usa mysql_unbuffered_query(), mysql_num_rows() non restituirà il valore corretto finché non sono recuperate tutte le righe del risultato.

Per motivi di compatibilità con il passato, anche mysql_numrows() può essere usata. Questo comunque è sconsigliato.

mysql_pconnect

Apre una connessione persiostente ad un server MySQL resource mysql_pconnect ( [string server [, string nome_utente [, string password [, int flag_client]]]]) Restituisce un identificativo di connessione MySQL valido in caso di successo oppure FALSE in caso di errore.

mysql_pconnect() stabilisce una connessione ad un server MySQL. I seguenti valori predefiniti sono usati per i parametri opzionali mancanti: server = 'localhost:3306', nome_utente = nome dell'utente prprietario del processo server e password = password vuota. Il parametro flag_client può essere una combinatione delle costanti MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE o MYSQL_CLIENT_INTERACTIVE.

Il parametro server può includere una numero di porta. Es. "hostname:porta" o un percorso ad un socket es. ":/percorso/a/socket" per il localhost.

mysql_pconnect() agisce in modo molto simile a mysql_connect() con due differenze principali.

Primo, quando si connette, la funzione tenta innanzitutto di trovare una connessione (persistente) già aperta avente gli stessi host, username e password. Se viene trovata una connessione, viene restituito un identificativo a questa anziché aprirne una nuova.

Secondo, la connessione al server SQL non sarà chiusa quando l'esecuzione dello script termina. La connessione rimane invece aperta per usi futuri (mysql_close() non chiuderà le connessioni stabilite da mysql_pconnect()).

Questo tipo di link è perciò chiamato 'persistente'.

Nota: Notare che questo tipo di connessione funziona solo se si usa PHP come modulo.

Attenzione: l'uso di connessioni persistenti può richiedere un po' di messa a punto delle configurazioni di Apache e MySQL per assicurarsi di non eccedere il numero di connessioni consentite da MySQL.

mysql_ping

Esegue un ping su una connessione al server o riconnette se non non esiste la connessione bool mysql_ping ( [resource identificativo_connessione]) mysql_ping() controlla se una connessione al server funziona o meno. Se questa è caduta, viene tentata una riconnessione automatica. Questa funzione può essere usata dagli script che rimangono inattivi per un lungo periodo per controllare se il server ha chiuso la connessione o meno e riconnettersi se necessario. mysql_ping() restituisce TRUE se la connessione al server è funzionante, altrimenti FALSE.

mysql_query

Invia una query MySQL resource mysql_query ( string query [, resource identificativo_connessione [, int modo_risultato]]) mysql_query() invia una query al database attualmente attivo sul server associato all'identificativo di conmnessione specificato. Se identificativo_connessione non è specificato, viene considerata l'ultima connessione aperta. Se nessuna connessione è aperta, la funzione prova a stabilire una connessione come se mysql_connect() fosse richiamata senza argomenti ed usa questa.

Il paramentro opzionale modo_risultato può essere MYSQL_USE_RESULT e MYSQL_STORE_RESULT. Il valore predefinito MYSQL_STORE_RESULT, così il risultato è bufferato.

Nota: La stringa della query non dovrebbe terminare con un punto e virgola.

Solo per le istruzioni SELECT, SHOW, EXPLAIN o DESCRIBE mysql_query() restituisce un identificativo di risorsa o FALSE se la query non è stata eseguita correttamente. Per altri tipi di istruzioni SQL, mysql_query() restituisce TRUE in caso di successo e FALSE in caso di errore. Un valore restituito diverso da FALSE indica che la query era lecita ed è stata eseguita dal server. Questo non indica niente riguardo il numero di righe coinvolte o restituite. è assolutamente possibile che una query abbia successo ma che non coinvolga o restituisca nessuna riga.

mysql_query() fallisce e restituisce FALSE anche se non si hanno i permessi per accedere alle tabelle cui la query fa riferimento.

Page 35: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

31 PHP

Assumendo che la query abbia successo, si può richiamare mysql_num_rows() per scoprire quante righe sono state restituite da un'istruzione SELECT o mysql_affected_rows() per scoprire quante righe sono state coinvolte da un'istruzione DELETE, INSERT, REPLACE o UPDATE.

Solo per le istruzioni SELECT, SHOW, DESCRIBE o EXPLAIN, mysql_query() restituisce un nuovo identificativo di risultato che si può passare a mysql_fetch_array() e ad altre funzioni che si occupano dei risultati delle tabelle. Quando si conclude il trattamento del risultato, si possono liberare le risorse associate ad esso richiamando mysql_free_result(). Comunqe la memoria sarà liberata automaticamente Al termnine dell'esecuzione dello script.

mysql_real_escape_string

Aggiunge le sequenze di escape ai caratteri speciali in una stringa per l'uso in una istruzione SQL, tenendo conto dell'attuale set di caratteri della connessione. string mysql_real_escape_string ( string stringa_seza_escape [, resource identificativo_connessione]) Questa funzione aggiunge le sequenza di escape ai caratteri speciali in stringa_senza_escape, tenendo conto dell'attuale set di caratteri della connessione in modo che sia sicuro usarla in mysql_query().

Nota: mysql_real_escape_string() non aggiunge le sequenze di escape a % ed a _.

mysql_result

Ottiene i dati dal risultato mixed mysql_result ( resource risultato, int campo [, mixed campo]) mysql_result() restituisce i contenuti di una cella da un risultato MySQL. L'argomento campo può essere l'indice o il nome del campo oppure il nome della tabella ed il nome del campo separati da un punto (nome_tabella.nome_campo). Se il nome della colonna ha un alias ('select foo as bar from...'), usare l'alias al posto del nome della colonna.

Quando si lavora con un risultato di grandi dimensioni, si dovrebbero considerare l'uso delle funzioni che caricano l'intera riga (specificate di seguito). Poiché queste funzioni restituiscono i contenuti di celle multiple in una chiamata a funzione, sono MOLTO più veloci di mysql_result(). Notare anche che specificare un indice numerico per l'argomento campo è molto più veloce che specificare un argomento del tipo nome_di_campo o nome_tabella.nome_campo.

Le chiamate a mysql_result() non dovrebbero esserse mescolate con chiamate ad altre funzioni che hanno a che fare con i risultati.

Alternative raccomandate per alte prestazioni: mysql_fetch_row(), mysql_fetch_array() e mysql_fetch_object().

mysql_select_db

Seleziona un database MySQL bool mysql_select_db ( string nome_database [, resource identificativo_connessione]) Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

mysql_select_db() imposta il database attualmente attivo sul server associato all'identificativo di connessione specificato. Se nessin identificativo di connesione è specificato, viene considerata l'ultima connessione aperta. Se nessuna connessione è aperta, la funzione proverà a stabilire una connessione come se mysql_connect() fosse richiamata senza argomenti ed userà questa.

Ogni chiamata successiva a mysql_query() sarà fatta sul database attivo.

mysql_stat

Ottiene l'attuale stato del sistema string mysql_stat ( [resource identificativo_connessione]) mysql_stat() restituisce l'attuale stato del server.

Nota: mysql_stat() attualmente restituisce solo le seguenti informazioni: uptime, thread, query, tabelle aperte, tabelle svuotate e query al secondo. Per una lista completa delle altre variabili di stato si usi il comando SQL SHOW STATUS.

mysql_tablename

Ottiene il nome della tabella string mysql_tablename ( resource risultato, int i) mysql_tablename() prende il puntatore risultato dalla funzione mysql_list_tables() come un indice intero e restituisce il nome di una tabella. La funzione mysql_num_rows() può essere usata per determinare il numero di tabelle nel risultato puntatore. Usare la funzione mysql_tablename() per esplorare questo risultato puntatore o qualsiasi funzione per i risultati delle tabelle, come mysql_fetch_array().

Page 36: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

32 PHP

mysql_thread_id

Restituisce l'attuale thread ID int mysql_thread_id ( [resource identificativo_connessione]) mysql_thread_id() restituisce l'attuale thread ID. Se La connessione è persa a ci si riconnette con mysql_ping(), il thread ID cambia. Questo significa che non si dovrebbe ottenere il thread ID e memorizzarlo per impieghi successivi. Si dovrebbe rilevare il thread ID quando è necessario.

mysql_unbuffered_query

Invia una query SQL a MySQL senza caricare e bufferare le righe risultanti resource mysql_unbuffered_query ( string query [, resource identificativo_connessione [, int modo_risultato]]) mysql_unbuffered_query() invia una query SQL query a MySQL senza caricare e bufferare le righe risultanti automaticamente come fa mysql_query(). Da una parte, questo risparmia un considerevole quantità di memoria con le query SQL che producono risulati di grandi dimensioni. Dall'altra parte, si può iniziare l'elaborazione dei risultati immediatamente dopo che la prima riga è stata recuperata: non si deve attendere finché la query SQL sia completamente eseguita. Quando si usano diverse connessioni a database, si deve specificare il paramentro opzionale identificativo_connessione.

Il parametro opzionale modo_risultato può essere MYSQL_USE_RESULT e MYSQL_STORE_RESULT. Il valore predefinito è MYSQL_USE_RESULT, quindi il risultato non è bufferato.

Nota: I benefici di mysql_unbuffered_query() hanno un costo: non si può usare mysql_num_rows() su un risultato restituito da mysql_unbuffered_query(). Inoltre si debbono caricare tutte le righe risultanti da una query SQL non bufferata prima di poter inviare una nuova query SQL a MySQL.

Page 37: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

33 PHP

Funzioni Stringa

addcslashes

Quote string with slashes in a C style string addcslashes ( string str, string charlist) Returns a string with backslashes before characters that are listed in charlist parameter. It escapes \n, \r etc. in C-like style, characters with ASCII code lower than 32 and higher than 126 are converted to octal representation.

Be careful if you choose to escape characters 0, a, b, f, n, r, t and v. They will be converted to \0, \a, \b, \f, \n, \r, \t and \v. In PHP \0 (NULL), \r (carriage return), \n (newline) and \t (tab) are predefined escape sequences, while in C all of these are predefined escape sequences.

charlist like "\0..\37", which would escape all characters with ASCII code between 0 and 31.

When you define a sequence of characters in the charlist argument make sure that you know what characters come between the characters that you set as the start and end of the range.

Also, if the first character in a range has a lower ASCII value than the second character in the range, no range will be constructed. Only the start, end and period characters will be escaped. Use the ord() function to find the ASCII value for a character.

addslashes

Quote string with slashes string addslashes ( string str) Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

bin2hex

Convert binary data into hexadecimal representation string bin2hex ( string str) Returns an ASCII string containing the hexadecimal representation of str. The conversion is done byte-wise with the high-nibble first.

chop

Alias of rtrim() This function is an alias of rtrim().

chr

Return a specific character string chr ( int ascii) Returns a one-character string containing the character specified by ascii.

chunk_split

Split a string into smaller chunks string chunk_split ( string body [, int chunklen [, string end]]) Can be used to split a string into smaller chunks which is useful for e.g. converting base64_encode output to match RFC 2045 semantics. It inserts end (defaults to "\r\n") every chunklen characters (defaults to 76). It returns the new string leaving the original string untouched.

convert_cyr_string

Convert from one Cyrillic character set to another string convert_cyr_string ( string str, string from, string to)

Page 38: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

34 PHP

This function returns the given string converted from one Cyrillic character set to another. The from and to arguments are single characters that represent the source and target Cyrillic character sets. The supported types are:

count_chars

Return information about characters used in a string mixed count_chars ( string string [, int mode]) Counts the number of occurrences of every byte-value (0..255) in string and returns it in various ways. The optional parameter Mode default to 0. Depending on mode count_chars() returns one of the following:

0 - an array with the byte-value as key and the frequency of every byte as value.

1 - same as 0 but only byte-values with a frequency greater than zero are listed.

2 - same as 0 but only byte-values with a frequency equal to zero are listed.

3 - a string containing all used byte-values is returned.

4 - a string containing all not used byte-values is returned.

crc32

Calculates the crc32 polynomial of a string int crc32 ( string str) Generates the cyclic redundancy checksum polynomial of 32-bit lengths of the str. This is usually used to validate the integrity of data being transmitted.

Nota: Because PHP's integer type is signed, and many crc32 checksums will result in negative integers, you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned crc32 checksum.

crypt

One-way string encryption (hashing) string crypt ( string str [, string salt]) crypt() will return an encrypted string using the standard Unix DES-based encryption algorithm or alternative algorithms that may be available on the system. Arguments are a string to be encrypted and an optional salt string to base the encryption on. See the Unix man page for your crypt function for more information.

If the salt argument is not provided, one will be randomly generated by PHP.

Some operating systems support more than one type of encryption. In fact, sometimes the standard DES-based encryption is replaced by an MD5-based encryption algorithm. The encryption type is triggered by the salt argument. At install time, PHP determines the capabilities of the crypt function and will accept salts for other encryption types. If no salt is provided, PHP will auto-generate a standard two character salt by default, unless the default encryption type on the system is MD5, in which case a random MD5-compatible salt is generated. PHP sets a constant named CRYPT_SALT_LENGTH which tells you whether a regular two character salt applies to your system or the longer twelve character salt is applicable.

If you are using the supplied salt, you should be aware that the salt is generated once. If you are calling this function recursively, this may impact both appearance and security.

The standard DES-based encryption crypt() returns the salt as the first two characters of the output. It also only uses the first eight characters of str, so longer strings that start with the same eight characters will generate the same result (when the same salt is used).

On systems where the crypt() function supports multiple encryption types, the following constants are set to 0 or 1 depending on whether the given type is available:

CRYPT_STD_DES - Standard DES-based encryption with a two character salt

CRYPT_EXT_DES - Extended DES-based encryption with a nine character salt

CRYPT_MD5 - MD5 encryption with a twelve character salt starting with $1$

CRYPT_BLOWFISH - Blowfish encryption with a sixteen character salt starting with $2$

Nota: There is no decrypt function, since crypt() uses a one-way algorithm.

echo

Output one or more strings void echo ( string arg1 [, string argn...]) Outputs all parameters.

Page 39: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

35 PHP

echo() is not actually a function (it is a language construct) so you are not required to use parentheses with it. In fact, if you want to pass more than one parameter to echo, you must not enclose the parameters within parentheses. It is not possible to use echo() in a variable function context.

echo() also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign.

explode

Split a string by string array explode ( string separator, string string [, int limit]) Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string separator. If limit is set, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

If separator is an empty string (""), explode() will return FALSE. If separator contains a value that is not contained in string, then explode() will return an array containing string.

Nota: Although implode() can, for historical reasons, accept its parameters in either order, explode() cannot. You must ensure that the separator argument comes before the string argument.

fprintf

Write a formatted string to a stream int fprintf ( resource handle, string format [, mixed args]) Write a string produced according to the formatting string format to the stream resource specified by handle..

The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to fprintf(), sprintf(), and printf().

Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:

An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below.

An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified.

An optional number, a width specifier that says how many characters (minimum) this conversion should result in.

An optional precision specifier that says how many decimal digits should be displayed for floating-point numbers. This option has no effect for other types than float. (Another function useful for formatting numbers is number_format().)

A type specifier that says what type the argument data should be treated as. Possible types:

% - a literal percent character. No argument is required.

b - the argument is treated as an integer, and presented as a binary number.

c - the argument is treated as an integer, and presented as the character with that ASCII value.

d - the argument is treated as an integer, and presented as a (signed) decimal number.

u - the argument is treated as an integer, and presented as an unsigned decimal number.

f - the argument is treated as a float, and presented as a floating-point number.

o - the argument is treated as an integer, and presented as an octal number.

s - the argument is treated as and presented as a string.

x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).

X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

htmlspecialchars

Convert special characters to HTML entities string htmlspecialchars ( string string [, int quote_style [, string charset]]) Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead.

This function is useful in preventing user-supplied text from containing HTML markup, such as in a message board or guest book application. The optional second argument, quote_style, tells the function what to do with single and double quote characters. The default mode, ENT_COMPAT, is the backwards compatible mode which only translates the double-quote character and leaves the single-quote untranslated. If ENT_QUOTES is set, both single and double quotes are translated and if ENT_NOQUOTES is set neither single nor double quotes are translated.

The translations performed are:

'&' (ampersand) becomes '&amp;'

Page 40: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

36 PHP

'"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.

''' (single quote) becomes '&#039;' only when ENT_QUOTES is set.

'<' (less than) becomes '&lt;'

'>' (greater than) becomes '&gt;'

Note that this function does not translate anything beyond what is listed above. For full entity translation, see htmlentities(). Support for the optional second argument was added in PHP 3.0.17 and PHP 4.0.3.

implode

Join array elements with a string string implode ( string glue, array pieces) Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.

Nota: implode() can, for historical reasons, accept its parameters in either order. For consistency with explode(), however, it may be less confusing to use the documented order of arguments.

join

Alias for implode()

This function is an alias of implode().

ltrim

Strip whitespace from the beginning of a string string ltrim ( string str [, string charlist]) Nota: The second parameter was added in PHP 4.1.0

This function returns a string with whitespace stripped from the beginning of str. Without the second parameter, ltrim() will strip these characters:

" " (ASCII 32 (0x20)), an ordinary space.

"\t" (ASCII 9 (0x09)), a tab.

"\n" (ASCII 10 (0x0A)), a new line (line feed).

"\r" (ASCII 13 (0x0D)), a carriage return.

"\0" (ASCII 0 (0x00)), the NUL-byte.

"\x0B" (ASCII 11 (0x0B)), a vertical tab.

You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

md5

Calculate the md5 hash of a string string md5 ( string str [, bool raw_output]) Calculates the MD5 hash of str using the RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. The hash is a 32-character hexadecimal number. If the optional raw_output is set to TRUE, then the md5 digest is instead returned in raw binary format with a length of 16.

Nota: The optional raw_output parameter was added in PHP 5.0.0 and defaults to FALSE

See also crc32(), md5_file(), and sha1().

number_format

Format a number with grouped thousands string number_format ( float number [, int decimals [, string dec_point [, string thousands_sep]]])

number_format() returns a formatted version of number. This function accepts either one, two or four parameters (not three):

If only one parameter is given, number will be formatted without decimals, but with a comma (",") between every group of thousands.

Page 41: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

37 PHP

If two parameters are given, number will be formatted with decimals decimals with a dot (".") in front, and a comma (",") between every group of thousands.

If all four parameters are given, number will be formatted with decimals decimals, dec_point instead of a dot (".") before the decimals and thousands_sep instead of a comma (",") between every group of thousands.

Nota: Only the first character of thousands_sep is used. For example, if you use foo as thousands_sep on the number 1000, number_format() will return 1f000.

ord

Return ASCII value of character int ord ( string string) Returns the ASCII value of the first character of string. This function complements chr().

parse_str

Parses the string into variables void parse_str ( string str [, array arr]) Parses str as if it were the query string passed via an URL and sets variables in the current scope. If the second parameter arr is present, variables are stored in this variable as array elements instead.

Nota: To get the current QUERY_STRING, you may use the variable $_SERVER['QUERY_STRING']. Also, you may want to read the section on variables from outside of PHP.

print

Output a string void print ( string arg) Outputs arg. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

print() is not actually a real function (it is a language construct) so you are not required to use parentheses with it.

printf

Output a formatted string void printf ( string format [, mixed args]) Produces output according to format, which is described in the documentation for sprintf().

rtrim

Strip whitespace from the end of a string string rtrim ( string str [, string charlist]) This function returns a string with whitespace stripped from the end of str. Without the second parameter, rtrim() will strip these characters:

" " (ASCII 32 (0x20)), an ordinary space.

"\t" (ASCII 9 (0x09)), a tab.

"\n" (ASCII 10 (0x0A)), a new line (line feed).

"\r" (ASCII 13 (0x0D)), a carriage return.

"\0" (ASCII 0 (0x00)), the NUL-byte.

"\x0B" (ASCII 11 (0x0B)), a vertical tab.

You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

sprintf

Return a formatted string string sprintf ( string format [, mixed args]) Returns a string produced according to the formatting string format.

The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to both sprintf() and printf().

Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:

Page 42: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

38 PHP

An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below.

An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified.

An optional number, a width specifier that says how many characters (minimum) this conversion should result in.

An optional precision specifier that says how many decimal digits should be displayed for floating-point numbers. This option has no effect for other types than float. (Another function useful for formatting numbers is number_format().)

A type specifier that says what type the argument data should be treated as. Possible types:

% - a literal percent character. No argument is required.

b - the argument is treated as an integer, and presented as a binary number.

c - the argument is treated as an integer, and presented as the character with that ASCII value.

d - the argument is treated as an integer, and presented as a (signed) decimal number.

u - the argument is treated as an integer, and presented as an unsigned decimal number.

f - the argument is treated as a float, and presented as a floating-point number.

o - the argument is treated as an integer, and presented as an octal number.

s - the argument is treated as and presented as a string.

x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).

X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

sscanf

Parses input from a string according to a format mixed sscanf ( string str, string format [, string var1]) The function sscanf() is the input analog of printf(). sscanf() reads from the string str and interprets it according to the specified format. If only two parameters were passed to this function, the values parsed will be returned as an array.

Any whitespace in the format string matches any whitespace in the input string. This means that even a tab \t in the format string can match a single space character in the input string.

str_pad

Pad a string to a certain length with another string string str_pad ( string input, int pad_length [, string pad_string [, int pad_type]]) This functions returns the input string padded on the left, the right, or both sides to the specified padding length. If the optional argument pad_string is not supplied, the input is padded with spaces, otherwise it is padded with characters from pad_string up to the limit.

Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT.

If the value of pad_length is negative or less than the length of the input string, no padding takes place.

str_repeat

Repeat a string string str_repeat ( string input, int multiplier) Returns input_str repeated multiplier times. multiplier has to be greater than or equal to 0. If the multiplier is set to 0, the function will return an empty string.

str_replace

Replace all occurrences of the search string with the replacement string mixed str_replace ( mixed search, mixed replace, mixed subject [, int &count]) This function returns a string or an array with all occurences of search in subject replaced with the given replace value. If you don't need fancy replacing rules, you should always use this function instead of ereg_replace() or preg_replace().

In PHP 4.0.5 and later, every parameter to str_replace() can be an array.

If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.

Page 43: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

39 PHP

If search and replace are arrays, then str_replace() takes a value from each array and uses them to do search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string; then this replacement string is used for every value of search.

str_shuffle

Randomly shuffles a string string str_shuffle ( string str) str_shuffle() shuffles a string. One permutation of all possible is created.

str_word_count

Return information about words used in a string mixed str_word_count ( string string [, int format]) Counts the number of words inside string. If the optional format is not specified, then the return value will be an integer representing the number of words found. In the event the format is specified, the return value will be an array, content of which is dependent on the format. The possible value for the format and the resultant outputs are listed below.

1 - returns an array containing all the words found inside the string.

2 - returns an associative array, where the key is the numeric position of the word inside the string and the value is the actual word itself.

For the purpose of this function, 'word' is defined as a locale dependent string containing alphabetic characters, which also may contain, but not start with "'" and "-" characters.

strchr

Alias for strstr() This function is an alias of strstr().

strcmp

Binary safe string comparison int strcmp ( string str1, string str2) Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

Note that this comparison is case sensitive.

strlen

Get string length int strlen ( string str) Returns the length of string.

strpos

Find position of first occurrence of a string int strpos ( string haystack, string needle [, int offset]) Returns the numeric position of the first occurrence of needle in the haystack string. Unlike the strrpos(), this function can take a full string as the needle parameter and the entire string will be used.

If needle is not found, strpos() will return boolean FALSE.

Attenzione: questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione.

strrchr

Find the last occurrence of a character in a string string strrchr ( string haystack, string needle) This function returns the portion of haystack which starts at the last occurrence of needle and goes until the end of haystack.

Page 44: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

40 PHP

Returns FALSE if needle is not found.

If needle contains more than one character, the first is used.

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

strrev

Reverse a string string strrev ( string string)

strtok

Tokenize string string strtok ( string arg1, string arg2) strtok() splits a string (arg1) into smaller strings (tokens), with each token being delimited by any character from arg2. That is, if you have a string like "This is an example string" you could tokenize this string into its individual words by using the space character as the token.

Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string. To start over, or to tokenize a new string you simply call strtok with the string argument again to initialize it. Note that you may put multiple tokens in the token parameter. The string will be tokenized when any one of the characters in the argument are found.

strtolower

Make a string lowercase string strtolower ( string str) Returns string with all alphabetic characters converted to lowercase.

Note that 'alphabetic' is determined by the current locale. This means that in i.e. the default "C" locale, characters such as umlaut-A (Ä) will not be converted.

strtoupper

Make a string uppercase string strtoupper ( string string) Returns string with all alphabetic characters converted to uppercase.

Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.

strtr

Translate certain characters string strtr ( string str, string from, string to) string strtr ( string str, array replace_pairs) This function returns a copy of str, translating all occurrences of each character in from to the corresponding character in to and returning the result.

If from and to are different lengths, the extra characters in the longer of the two are ignored.

strtr() can be called with only two arguments. If called with two arguments it behaves in a new way: from then has to be an array that contains string -> string pairs that will be replaced in the source string. strtr() will always look for the longest possible match first and will *NOT* try to replace stuff that it has already worked on.

substr_count

Count the number of substring occurrences int substr_count ( string haystack, string needle) substr_count() returns the number of times the needle substring occurs in the haystack string.

Page 45: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

41 PHP

substr_replace

Replace text within a portion of a string string substr_replace ( string string, string replacement, int start [, int length]) substr_replace() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement. The result is returned.

If start is positive, the replacing will begin at the start'th offset into string.

If start is negative, the replacing will begin at the start'th character from the end of string.

If length is given and is positive, it represents the length of the portion of string which is to be replaced. If it is negative, it represents the number of characters from the end of string at which to stop replacing. If it is not given, then it will default to strlen( string ); i.e. end the replacing at the end of string.

substr

Return part of a string string substr ( string string, int start [, int length]) substr() returns the portion of string specified by the start and length parameters.

If start is non-negative, the returned string will start at the start'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth.

If start is negative, the returned string will start at the start'th character from the end of string.

If length is given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of string). If string is less than start characters long, FALSE will be returned.

If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative). If start denotes a position beyond this truncation, an empty string will be returned.

trim

Strip whitespace from the beginning and end of a string string trim ( string str [, string charlist]) This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:

" " (ASCII 32 (0x20)), an ordinary space.

"\t" (ASCII 9 (0x09)), a tab.

"\n" (ASCII 10 (0x0A)), a new line (line feed).

"\r" (ASCII 13 (0x0D)), a carriage return.

"\0" (ASCII 0 (0x00)), the NUL-byte.

"\x0B" (ASCII 11 (0x0B)), a vertical tab.

You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

ucfirst

Make a string's first character uppercase string ucfirst ( string str) Returns a string with the first character of str capitalized, if that character is alphabetic.

Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.

ucwords

Uppercase the first character of each word in a string string ucwords ( string str) Returns a string with the first character of each word in str capitalized, if that character is alphabetic.

Nota: The definition of a word is any string of characters that is immediately after a whitespace (These are: space, form-feed, newline, carriage return, horizontal tab, and vertical tab).

Page 46: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

42 PHP

wordwrap

Wraps a string to a given number of characters using a string break character. string wordwrap ( string str [, int width [, string break [, boolean cut]]]) Returns a string with str wrapped at the column number specified by the (optional) width parameter. The line is broken using the (optional) break parameter.

wordwrap() will automatically wrap at column 75 and break using '\n' (newline) if width or break are not given.

If the cut is set to 1, the string is always wrapped at the specified width. So if you have a word that is larger than the given width, it is broken apart. (See second example).

Page 47: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

43 DELPHI

Componenti data-aware Delphi Sono presentate le principali proprietà ed attributi dei componenti per l’accesso ai database via ADO e Interbase.

Componenti ADO

TADOConnection TADOConnection encapsulates the ADO connection object. Use TADOConnection for connecting to ADO data stores. The connection provided by a single TADOConnection component can be shared by multiple ADO command and dataset components through their Connection properties.

TADOConnection allows you to control the attributes and conditions of a connection to a data store. Use the properties of TADOConnection to control such attributes as record locking scheme (optimistic versus pessimistic), cursor type, cursor location, isolation level, and connection timeout. Methods are also provided for implementing transactions and retrieving metadata about the database to which this component connects.

Properties Description

Attributes property Attributes: TXactAttributes;

Set Attributes to specify whether a connection object performs retaining commits or retaining aborts. The two behaviors are independent of each other.

Attributes can contain one of the two TXactAttribute values (xaCommitRetaining and xaAbortRetaining), both values, or neither value.

Connected property Connected: Boolean;

Set Connected to True to establish a connection to an ADO data store without opening a dataset. Set Connected to False to close a connection. The default value for Connected is False.

An application can check Connected to determine the current status of a connection. If Connected is True, the connection is active; if False, and the KeepConnection property is also False, then the connection is inactive.

Connected can also be used in a program to determine the success of a call to the Open method (a True value in Connected) or the Close method (a False value).

ConnectionString property ConnectionString: WideString;

Set ConnectionString to specify the information needed to connect the ADO connection component to the data store. The value used for ConnectionString consists of one or more arguments ADO uses to establish the connection. Specify multiple arguments as a list with individual arguments separated by semicolons.

A connection string may be saved to file for later use. Specify only the name of such a file in ConnectionString to reuse a saved connection string.

The connection string may also contain login information such as user ID and password, for automated logins.

When explicitly passing login information through either the Open method or the ConnectionString, the LoginPrompt property should be set to False to prevent an unnecessary login dialog.

ADO supports the following four arguments for connection strings. Any other arguments (such as a user ID and password) are not processed by ADO and simply passed on to the provider.

Argument Meaning

Provider The name of the provider to use for the connection.

File name The name of a file containing connection information.

Remote Provider The name of the provider to use for a client-side connection.

Remote Server The path name of the server to use for a client-side connection.

Note: After opening a connection, the contents of ConnectionString may be changed by ADO. One example of this behavior is when ADO-defined arguments are mapped to their provider equivalents.

IsolationLevel property IsolationLevel: TIsolationLevel;

Use IsolationLevel to specify the transaction isolation level for a connection. The transaction isolation level determines how a transaction interacts with other simultaneous transactions when they work with the same tables, and how much a transaction sees of the work performed by other transactions. The default value for IsolationLevel is ilCursorStability.

Set IsolationLevel to a valid TIsolationLevel value prior to starting a new transaction. Read IsolationLevel after the transaction has been activated to determine the actual transaction isolation level used. It is possible that a server will force an isolation level other than that requested if the level requested is not supported.

KeepConnection property KeepConnection: Boolean;

Page 48: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

44 DELPHI

Use KeepConnection to specify whether an application remains connected to a database even if no associated dataset components are currently active. When KeepConnection is True (the default) the connection is maintained. For connections to remote database servers, or for applications that frequently open and close datasets, set KeepConnection to True to reduce network traffic, speed up applications, and avoid logging in to the server each time the connection is reestablished.

When KeepConnection is False a connection is dropped when there are no open datasets. Dropping a connection releases system resources allocated to the connection, but if a dataset is later opened that uses the database, the connection must be reestablished and initialized.

Methods Description

BeginTrans function BeginTrans: Integer;

Call BeginTrans to start a new transaction in the data store the ADO connection component is connected to.

BeginTrans returns a value of type Integer, indicating the nesting level of the new transaction.

A successful execution of BeginTrans triggers an OnBeginTransComplete event and sets the InTransaction property to True.

Note: The ADO connection object must have an active connection before BeginTrans can be used.

Cancel procedure Cancel;

Call Cancel to abort an attempt to connect to an ADO data store. To use cancel, the connection attempted must be asynchronous (the ConnectOptions property must be set to coAsyncConnect).

Cancel must be used after an attempt to connect is initiated by calling the Open method (or setting Connected to True) and before the connection has been successfully made or has timed out.

CommitTrans procedure CommitTrans;

Call CommitTrans to save any changes made during the current transaction and to end the transaction.

A successful execution of CommitTrans triggers an OnCommitTransComplete event and sets the InTransaction property to False.

Execute function Execute(const CommandText: WideString; ExecuteOptions: TExecuteOptions = []): _RecordSet; overload; procedure Execute(const CommandText: WideString; var RecordsAffected: Integer; ExecuteOptions: TExecuteOptions = [eoExecuteNoRecords]); overload;

Call Execute to execute a command using the ADO connection object.

CommandText is the command to execute.

ExecuteOptions is a TExecuteOptions value that specifies the characteristics of the command execution.

Execute returns a recordset if the command executed is one that generates a recordset.

RecordsAffected indicates the number of records, if the command operates on data, that are affected by the command after execution.

GetProcedureNames procedure GetProcedureNames(List: TStrings);

Populates a string list with the names of stored procedures in the database.

Call GetProcedureNames to retrieve a list of stored procedures in the associated database. The names of the stored procedures are put into the already-existing string list object specified in the List parameter.

Note: Any contents already in the target string list object are eliminated and overwritten by the data produces by GetProcedureNames.

GetFieldNames procedure GetFieldNames(const TableName: String; List: TStrings);

Populates a string list with the names of fields in a table.

Call GetFieldNames to retrieve a list of fields in a table. The names of the fields are put into the already-existing string list object specified in the List parameter. Specify the table for which to retrieve the names of fields in the TableName property.

GetTableNames procedure GetTableNames(List: TStrings; SystemTables: Boolean = False);

Populates a string list with the names of tables in the database.

Call GetTableNames to retrieve a list of tables in the associated database.

List is the already-existing string list object into which the tables names are put.

Set SystemTables to indicate whether the list of table names should include the database’s system tables.

Note: Any contents already in the target string list object are eliminated and overwritten by the data produces by GetTableNames.

Open procedure Open; overload; procedure Open(const UserID: WideString; const Password: WideString); overload;

Call Open to initiate a connection to the database specified in the ConnectionString property.

UserID and Password parameters for Open can be optionally used to pass the user ID and login password to the database server at the same time the request is made to connect.

Page 49: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

45 DELPHI

Alternately, this login information may be passed in the value in ConnectionString.

When explicitly passing login information through either the Open method or the ConnectionString, the LoginPrompt property should be set to False to prevent an unnecessary login dialog.

OpenSchema procedure OpenSchema(const Schema: TSchemaInfo; const Restrictions: OleVariant; const SchemaID: OleVariant; DataSet: TADODataSet);

Call OpenSchema to open a connection and retrieve schema information from the associated provider. OpenSchema retrieves the schema information in the form of a recordset that can then be accessed through an ADO dataset component.

The Schema parameter is the type of schema information to retrieve, or in ADO terms, the query type.

The Restrictions parameter is an array of query constraints for the specified type of schema information. This lists the type of information requested for the entity specified by Schema. In ADO terms, the elements of the array list the criteria for the query type.

SchemaID is the GUID for a provider-schema schema query not defined by the OLE DB specification. This parameter is required if the Schema parameter is set to siProviderSpecific, otherwise it is not used.

DataSet is the ADO dataset component (such as a TADOTable) into the Recordset property of which the schema information is retrieved and through which the information is subsequently accessed. After OpenSchema loads the ADO dataset component with the schema information, use the standard navigation methods like First and Next to traverse the rows of data. Use the Fields property or the FieldByName method of the dataset component to read the value of any one column. Alternately, the schema data may be displayed using visual data-aware controls and a TDataSource.

RollbackTrans procedure RollbackTrans;

Call RollbackTrans to cancel any changes made during the current transaction and to end the transaction.

A successful execution of RollbackTrans triggers an OnRollbackTransComplete event and sets the InTransaction property to True.

Close procedure Close;

Call Close to disconnect from the remote source of database information. Before the connection component is deactivated, all associated datasets are closed. Calling Close is the same as setting the Connected property to False.

In most cases, closing a connection frees system resources allocated to the connection.

Note: If a previously active connection is closed and then reopened, any associated datasets must be individually reopened; reopening the connection does not automatically reopen associated datasets.

TADOCommand The TADOCommand represents the ADO Command object. Use TADOCommand for issuing commands against a data store accessed through an ADO (ActiveX Data Objects) provider.

The TADOCommand component executes the command specified in its CommandText property. One command may be executed at a time. Parameters, if the command includes them, are specified in its Parameters property. The command is executed by a call to the Execute method.

TADOCommand can either use a TADOConnection object to connect to a data store (through its Connection property) or connect directly to the data store if the connection information is specified in the ConnectionString property.

TADOCommand is most often used for executing data definition language (DDL) SQL commands or to execute a stored procedure that does not return a result set. For SQL statements that return a result set, TADODataSet, TADOQuery, or TADOStoredProc is better suited. The Execute method of TADOCommand is, however, capable of returning a recordset. To use that recordset, however, you will need a separate ADO dataset component.

As a close representation of the ADO Command object, many of the TADOCommand properties and methods have the same name as those of the ADO Command object and serve the same purpose. For example, the CommandType property and Execute methods are the same in both the TADOCommand component and ADO Command object. Note that subsequent versions of ADO may introduce changes in the underlying ADO command object, which will change the behavior of TADOCommand. As a result, you may want to view the Microsoft Data Store SDK documentation for additional information about the behavior of TADOCommand.

Properties Description

CommandText property CommandText: WideString;

Use CommandText to specify the command to execute using the ADO command component. CommandText is a textual representation of the command such as an SQL statement, a table name, or the name of a stored procedure to execute.

If the command includes parameters, as might be the case with an SQL statement or stored procedure, access the them through the Parameters property.

CommandTimeout property CommandTimeout: Integer;

Use CommandTimeout to indicate the time, in seconds, that can elapse before an attempt to

Page 50: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

46 DELPHI

execute the command is considered unsuccessful. The default value for CommandTimeout is 30.

If a command is successfully executed prior to the expiration of the seconds specified, CommandTimeout has no effect.

CommandType property CommandType: TCommandType;

Set CommandType to indicate the type of command that is contained in the CommandText property. The value in CommandType should agree with that of CommandText. For instance, if CommandText is the name of a table, CommandType should be cmdTable or cmdTableDirect.

The default value of CommandType is cmdUnknown. While CommandType may be left as cmdUnknown for all commands, setting CommandType to explicitly indicate the type of the command results in better performance. When CommandType is cmdUnknown, ADO must evaluate the command to determine its type, which slows the operation.

Note: The TCommandType constants cmdTable, cmdTableDirect, and cmdOpenFile should not be used with commands executed from a TADOCommand component.

Connection property Connection: TADOConnection;

Set Connection to specify the TADOConnection the command component uses to connect to the data store.

Note: the connection of an ADO command component to a data store can either be through a TADOConnection specified in the Connection property or directly through the connection string specified in ConnectionString. These two properties are mutually exclusive.

ConnectionString Specifies the connection information for the database.

ExecuteOptions property ExecuteOptions: TExecuteOptions;

Set ExecuteOptions to control the characteristics of a command executed from the ADO dataset component.

ParamCheck property ParamCheck: Boolean;

Set ParamCheck to specify whether or not the Parameters property is initialized using ":Param" style parameters in an SQL statement specified in the CommandText property. If the SQL statement in CommandText only contains "?" style parameters, the Parameters property will only be initialized if the OLE DB provider returns parameter information for an SQL command. Otherwise, the parameters must be explicitly created using the TParameters.CreateParameter method.

Parameters property Parameters: TParameters;

Access Parameters at runtime to view and set parameter names, values, and data types dynamically (at design time use the collection editor for the Parameters property to set parameter information). Parameters is a zero-based array of TParameter parameter records. Index specifies the array element to access.

Note: Parameters is only applicable when the ADO command object issues an SQL statement or executes a stored procedure (the CommandType is cmdText or cmdStoredProc) and parameters are actually used in the SQL statement or stored procedure.

Prepared property Prepared: WordBool;

Set Prepared before calling the Execute method to specify whether ADO prepares the command. If Prepared is set to True and the command component is connected to a data store, ADO prepares the command before executing it. If Prepared is set to False, ADO does not prepare the command.

The default value of Prepared is False.

Methods Description

Assign procedure Assign(Source: TPersistent); override;

Call Assign to copy the property values from one ADO command object to the properties of the current ADO command object.

Source is the ADO command object from which property values are copied. Source must be another TADOCommand object or an instance of a descendant class.

Assign copies the values of the following properties specific to ADO command objects:

Connection, if assigned; otherwise the ConnectionString property is copied. CommandText. CommandTimeout. CommandType. Prepared. Parameters.

Cancel procedure Cancel;

Call Cancel abort the execution of a command executed by the command component. To use Cancel to abort a command, the command by have been executed asynchronously (the eoAsyncExecute TExecuteOption must have been used). If the command is not asynchronous an exception is raised. Use the command component’s ExecuteOptions to specify that a command is executed asynchronously.

Note: To successfully cancel a command, Cancel must be called before the number of seconds specified in CommandTimeout have expired.

Execute function Execute: _Recordset; overload; function Execute(const Parameters: OleVariant): _Recordset; overload; function Execute(var RecordsAffected: Integer; const Parameters: OleVariant): _RecordSet; overload;

Page 51: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

47 DELPHI

Call Execute to immediately execute the command specified in the CommandText property.

RecordsAffected indicates the number of records, if the command operates on data, that are affected by the command after execution.

Parameters is a collection of parameters for the command, unnecessary if the command does not use any parameters.

When a command is executed that creates a recordset, Execute returns the recordset and it must be accessed through an ADO dataset component. To do this, assign the return value of Execute directly to the recordset property of an ADO data set component.

TADOTable TADOTable is a dataset component that encapsulates a table accessed through an ADO data store.

Use TADOTable to access data in a single database table using ADO. TADOTable provides direct access to every record and field in an underlying database table. An ADO table component can also work with a subset of records within a database table using ranges and filters.

Properties Description

MasterSource property MasterSource: TDataSource;

Use MasterSource to specify the name of the data source component whose DataSet property identifies a dataset to use as a Master table in establishing a Master-Detail relationship between this table and another one.

After setting the MasterSource property, specify which fields to use in the master table by setting the MasterFields property. At runtime each time the current record in the master table changes, the new values in those fields are used to select corresponding records in this table for display.

Note: At design time choose an available data source from the MasterSource property’s drop-down list in the Object Inspector.

ReadOnly property ReadOnly: Boolean

Use the ReadOnly property to prevent users from updating, inserting, or deleting data through the TADOTable. By default, ReadOnly is False, meaning users can alter a table’s data.

TableDirect property TableDirect: Boolean read GetTableDirect write SetTableDirect default False;

Set TableDirect to specify whether the table is accessed simply via its name or whether a background SQL statement is used. Not all providers support accessing a table by its name and require that this access be done with a SELECT statement. If TableDirect is True the data retrieval request uses a background SQL statement and all columns are simply returned. If it is False, the TADOTable component creates a SELECT statement to retrieve the table's data. The default value of TableDirect is False.

TableName property TableName: WideString;

Use TableName to specify the base table in a database on which the ADO table component operates. Data is retrieved from and changes written to this base table.

Before setting or changing the value of TableName, you should deactivate the ADO table component by calling its Close method or setting its Active property to False.

At design-time, if a valid connection to a database can be established, the Object Inspector provides a drop-down list of names of available tables.

Connection Specifies the ADO connection component to use.

ConnectionString Specifies the connection information for the data store.

CursorLocation property CursorLocation: TCursorLocation;

Use CursorLocation to indicate whether the cursors that use the connection object to connect to the ADO datastore use a client-side or server-side cursor library. CursorLocation only affects connections opened after the property is set. The default value for CursorLocation is clUseClient.

A client-side cursor offers more flexibility. All data is retrieved to the local machine and then operated on there, allowing operations not normally supported by servers like sorting and resorting the data and additional filtering. SQL statements are executed at the server, so for statements that restrict the result set with a WHERE clause, only the reduced result set is retrieved to a local cursor.

A server-side cursor offers less flexibility, but may be more advantageous (or necessary) for large result sets. Using a server-side cursor becomes necessary when the sheer size of a result set exceeds the available disk space that would be needed to create the client-side cursor. Also, many servers only support unidirectional cursors. This would preclude moving the record pointer in the dataset backward (even one record) through the result set.

CursorType property CursorType: TCursorType;

Set CursorType to indicate the type of cursor the ADO dataset uses for the recordset when it is opened. CursorType must be set prior to activating the dataset component. Among other cursor aspects, CursorType affects directional scrolling through a recordset and the visibility of changes made by other users.

The default value of CursorType is ctKeyset.

MasterFields property MasterFields: String;

Page 52: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

48 DELPHI

Use MasterFields after setting the MasterSource or DataSource property to specify the names of one or more fields in another, master, dataset that are used to establish a Master-Detail relationship between this dataset and the master dataset. The master dataset is specified by assigning its data source to the MasterSource or DataSource property.

MasterFields is a string containing one or more field names in the master dataset. When the datasets are related based on two fields, separate field names with semicolons.

Each time the current record in the master dataset changes, the new values in those fields are used to select corresponding records in this table for display.

Note: At design time, use the Field Link designer to establish the master-detail relationship between two tables.

MaxRecords property MaxRecords: Integer

Use MaxRecords to control the number of rows the provider for the ADO dataset component returns from the data source. Set MaxRecords to indicate the maximum number of rows. The default value for MaxRecords is 0 (zero), which places no limits on the result set.

RecNo property RecNo: Integer;

Read RecNo at runtime to determine the ordinal position of the active record within the dataset’s recordset. The dataset must be active for RecNo to have a valid value. When a dataset component is active, RecNo will be a number between one and the total number of rows in the recordset (reflected in the RecordCount property).

The value of RecNo for a given row in a recordset is relative to the rows that precede the current row. Thus, if a check of RecNo for a row indicates 10 and then a preceding row is deleted, a subsequent inspection of RecNo will show a new position of 9.

In the example below, the RecNo and RecordCount properties of a TCustomDataSet descendant are used to display the current record's number and the total number of records in a TStatusBar component. This would be done in a handler for the AfterScroll event of the ADO dataset component so that it is updated after each row pointer movement.

Set RecNo at runtime to move the record pointer to the record at the specified absolute position within the recordset. Use the value of the RecordCount property to determine the maximum number to which RecNo can be set.

Note: The number of rows indicated might be less than the total number of rows in a table. This can happen when the rows retrieved as a recordset for a dataset component are a conditional subset of the table.

RecordCount property RecordCount: Integer;

Examine RecordCount to determine the total number of records in the recordset of the dataset component. Applications might use this property with RecNo to iterate through all the records in a dataset, though typically record iteration is handled with calls to First, Last, MoveBy, and Prior using Eof and Bof to set the limits of row traversing.

The dataset component must be active for RecordCount to provide a valid number. Should ADO not be able to determine that actual number of rows, RecordCount will return a value of negative one (-1). Note: The number of rows indicated might be less than the total number of rows in a table. This can happen when the rows retrieved as a recordset for a dataset component are a conditional subset of the table.

RecordSize property RecordSize: Word;

RecordSize is an abstract property that is redeclared and implemented in descendant objects derived from TCustomADODataSet. For TCustomADODataSet, RecordSize is meaningless and always returns a value of 0 (zero).

Methods Description

Open Call Open to set the Active property for the dataset to True. When Active is True, data can be populated with data. It can read data from a database or other source (such as a provider). Depending on the CanModify property, active datasets can post changes. If an error occurs during the dataset open, dataset state is set to dsInactive, and any cursor is closed.

Close Call Close to set the Active property of a dataset to False. When Active is False, the dataset is closed; it cannot read or write data and data-aware controls can’t use it to fetch data or post edits. An application must close the dataset before changing properties that affect the status of the database or the controls that display data in an application. For example, to change the DataSource property for a dataset, the dataset must be closed. Closing the dataset puts it into the dsInactive state.

Requery procedure Requery(Options: TExecuteOptions = []);

Call Requery to refresh the recordset. Requery updates the dataset by re-executing the original command or SQL statement that produced the recordset. The effects of Requery are the same as calling the dataset’s Close method and then its Open method. However, there are circumstances when one means of refreshing the recordset is better than the other. The values in properties like CursorLocation, CursorType, and LockType cannot be changed while the dataset is open, so Requery can only refresh the recordset using the existing values in these properties. To refresh the recordset using different values for these properties, effect the refresh using the Close and Open methods. Options is a TExecuteOptions value that specifies the characteristics of the command execution affected by the requery that produces the recordset for the dataset.

Page 53: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

49 DELPHI

TADOQuery TADOQuery provides the means for issuing SQL against an ADO data store.

Use TADOQuery to access one or more tables in a data store using SQL statements.

Retrieve data from tables in an ADO data store using SELECT statements. Perform actions on tables and other metadata objects in an ADO data store with statements like INSERT, DELETE, UPDATE, ALTER TABLE, and CREATE TABLE. Execute stored procedures.

Properties Description

DataSource property DataSource: TDataSource;

Set DataSource to automatically fill parameters in a query with fields values from another dataset. Parameters that have the same name as fields in the other dataset are filled with the field values. Parameters with names that are not the same as fields in the other dataset do not automatically get values, and must be programmatically set.

If the SQL statement contains parameters with the same name as fields in the other dataset, do not manually set values for these parameters. Any values programmatically set, such as by using the Parameters property or the ParamByName method, will be overridden with automatic values. Parameters of other names must be programmatically given values. These parameters are unaffected by setting DataSource.

DataSource can be set at runtime or at design-time using the Object Inspector. At design-time, select the desired TDataSource from the drop-down list or type in the name.

RowsAffected property RowsAffected: Integer;

Inspect RowsAffected to determine how many rows were updated or deleted by the last query operation. If no rows were updated or deleted, RowsAffected has a value of zero. RowsAffected will have a value of –1 if the execution of the SQL statement could not be executed due to an error condition. This latter situation would typically follow the raising of an exception.

SQL property SQL: TStrings;

Use SQL to provide the SQL statement that an ADO query component executes when its ExecSQL or Open method is called.

The SQL statement provided to the SQL property may contain replaceable parameters, following standard ADO syntax conventions. Parameters are created and stored in the Parameters property.

At design-time, edit the SQL statement using the property editor invoked by clicking the ellipsis button of the property in the Object Inspector. At runtime, use properties and methods of string list objects to clear the current contents, add new contents, or to modify existing contents.

Note: Delphi does not evaluate the SQL sent to the database via a TADOQuery component. The SQL used must be valid for the particular database type accessed via ADO. Any error messages passed back to the application will have originated at the ADO or database level, and so will have error codes and messages specific to those systems.

Prepared property Prepared: Boolean;

Specifies whether the command is prepared before execution.

Set Prepared before calling the Open method to specify whether ADO prepares the command used to create the dataset’s recordset. If Prepared is set to True and the dataset component is connected to a data store, ADO prepares the command before executing it. If Prepared is set to False, ADO does not prepare the command.

The default value of Prepared is False.

Methods Description

ExecSQL function ExecSQL: Integer;

Call ExecSQL to execute the SQL statement currently assigned to the SQL property. Use ExecSQL to execute queries that do not return a cursor to data (such as INSERT, UPDATE, DELETE, and CREATE TABLE).

ExecSQL returns an integer value reflecting the number of rows affected by the executed SQL statement.

Note: For SELECT statements, call Open instead of ExecSQL or set the Active property to True.

To speed performance, an application should ordinarily prepare the query by setting the Prepared property to True before calling ExecSQL for the first time.

Open Opens the dataset.

Close Closes a dataset.

Requery Refreshes the recordset.

Page 54: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

50 DELPHI

Componenti Interbase

TIBDatabase TIBDatabase encapsulates an InterBase database connection.

Use TIBDatabase to encapsulate an InterBase database connection. All TIBCustomDataSet descendants and TIBSQL use the TIBDatabase component to gain access to databases.

Properties Description

Connected property Connected : Boolean;

Set Connected to True to establish a database connection without opening a dataset. Set Connected to False to close a database connection. An application can check Connected to determine the current status of a database connection. If Connected is True, the database connection is active; if False, then the connection is inactive.

DatabaseName property DatabaseName: String;

Use DatabaseName to specify the name of the database to use with a database component. For local InterBase databases, this can be a filename.

To connect to an InterBase database on a remote server using TCP/IP the syntax is <server_name>:<filename>.

To connect to an InterBase database on a remote server using NetBEUI, the syntax is: \\<server_name>\<filename>.

To connect to an InterBase database on a remote server using SPX, the syntax is: <server_name>@<filename>.

DefaultTransaction property DefaultTransaction: TIBTransaction;

Use DefaultTransaction to set or return the default database transaction.

A single database connection can manage one or more transactions. DefaultTransaction is a convenient way to specify a default transaction to a database connection.

IdleTimer property IdleTimer: Integer;

Use IdleTimer to indicate how long the database should wait before automatically terminating the connection.

Params property Params: TStrings;

Use Params to specify the database parameters to pass to the InterBase server.

Database parameters are passed to the server as text in order to establish the connection. For example:

user_name=sysdba password=masterkey sql_role_name=finance

TIBTransaction TIBTransaction provides discrete transaction control over a one or more database connections in a database application.

All TIBCustomDataSet descendants and TIBSQL need to use a transaction along with a database component to gain access to data in a database.

Note:In applications that connect an InterBaseExpress dataset to a client dataset, every query must be in its own transaction. You must use one transaction component for each query component.

Properties Description

Active property Active: Boolean;

Use Active to determine or set a transaction’s active state.

DatabaseCount property DatabaseCount: Integer;

Use DatabaseCount to determine the number of databases involved in a transaction.

Databases property Databases[Index: Integer]: TIBDatabase;

Use Databases to return the database at the given integer index.

DefaultAction type TTransactionAction = (taRollback, taCommit, taRollbackRetaining, taCommitRetaining); property DefaultAction: TTransactionAction;

Use DefaultAction to what action the transaction should take when the IdleTimer limit is met. The transaction action can be one of the following:

taRollback Rolls back the transaction

taCommit Commits the transaction

taRollbackRetaining Rolls back the transaction, but retains the current transaction

Page 55: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

51 DELPHI

contextNote: You must install InterBase 6 to use this feature.

taCommitRetaining Commits the transaction, but retains the current transaction context

DefaultDatabase property DefaultDatabase: TIBDatabase;

Use DefaultDatabase to set or return the default database for the transaction.

InTransaction property InTransaction: Boolean;

Examine InTransaction at run-time to determine if a database transaction is currently in progress. InTransaction is True if a transaction is in progress, False otherwise.

The value of InTransaction cannot be changed directly. Calling StartTransaction sets InTransaction to True. Calling Commit or Rollback sets InTransaction to False.

Params property Params: TStrings;

Use Params to examine and set parameters in the transaction parameter buffer. Refer to the Interbase API Guide for the names of the parameters to provide.

Methods Description

StartTransaction procedure StartTransaction;

Call StartTransaction to begin a new transaction against the database server. Before calling StartTransaction, an application should check the status of the InTransaction property. If InTransaction is True, indicating that a transaction is already in progress, a subsequent call to StartTransaction without first calling Commit or Rollback to end the current transaction raises an exception.

Updates, insertions, and deletions that take place after a call to StartTransaction are held by the server until an application calls Commit to save the changes or Rollback is to cancel them.

Commit procedure Commit;

Permanently stores updates, insertions, and deletions of data associated with the current transaction, and ends the current transactions.

Call Commit to permanently store to the database server all updates, insertions, and deletions of data associated with the current transaction and then end the transaction. The current transaction is the last transaction started by calling StartTransaction.

Note: Before calling Commit, an application may check the status of the InTransaction property. If an application calls Commit and there is no current transaction, an exception is raised.

CommitRetaining procedure CommitRetaining;

Call CommitRetaining to permanently store to the database server all updates, insertions, and deletions of data associated with the current transaction and then retain the transaction context. The current transaction is the last transaction started by calling StartTransaction.

Note: Before calling CommitRetaining, an application may check the status of the InTransaction property. If an application calls CommitRetaining and there is no current transaction, an exception is raised.

Rollback procedure Rollback;

Cancels all updates, insertions, and deletions for the current transaction and ends the transaction.

Call Rollback to cancel all updates, insertions, and deletions for the current transaction and to end the transaction. The current transaction is the last transaction started by calling StartTransaction.

Note: Before calling Rollback, an application may check the status of the InTransaction property. If an application calls Rollback and there is no current transaction, an exception is raised.

RollbackRetaining procedure RollbackRetaining;

Call RollbackRetaining to roll back to the database server all updates, insertions, and deletions of data associated with the current transaction and then retain the transaction context. The current transaction is the last transaction started by calling StartTransaction.

Note: Before calling RollbackRetaining, an application may check the status of the InTransaction property. If an application calls RollbackRetaining and there is no current transaction, an exception is raised. Note: You must install InterBase 6 to use this feature.

TIBTable TIBTable is a dataset component that encapsulates a database table.

Use TIBTable to access data in a single table or view. TIBTable provides direct access to every record and field in an underlying InterBase database table. A table component can also work with a subset of records within a database table using filters.

Properties Description

Transaction property Transaction: TIBTransaction;

Identifies the transaction under which the query executes.

Use Transaction to determine the transaction that contains any query this dataset executes. Set the properties of this transaction object to control how the transaction executes, or set the Transaction property to cause this dataset’s queries to be included in an existing transaction.

Page 56: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

52 DELPHI

TableName property TableName: String;

Use TableName to specify the name of the database relation this component encapsulates. To set TableName to a meaningful value, the Database property should already be set. If Database is set at design time, then select a valid table name from the TableName drop-down list in the Object Inspector.

Note: To set TableName, the Active property must be False.

CanModify property CanModify: Boolean;

Check the status of CanModify to determine if an application can modify a dataset in any way. If CanModify is True, the dataset can be modified. If CanModify is False, the table is read-only.

CanModify is set automatically when an application opens a table. If the ReadOnly property of a table component is True, then CanModify is set to False. CanModify can also be false because:

Another application currently has exclusive write access to the table. The table is read-only by database design.

Note: Even if CanModify is True, it is not a guarantee that a user will be able to insert or update records in a table. Other factors may come in to play, for example, SQL access privileges.

Active Specifies whether or not a dataset is open.

TIBQuery TIBQuery executes an InterBase SQL statement.

Use TIBQuery to access one or more tables in a database using SQL statements. The TIBQuery component provides a read-only dataset, and adapts well to the InterBase client/server environment. To update the result set that TIBQuery represents, use this component in conjunction with a TIBUpdateSQL component.

Query components are useful because they can

• Access more than one table at a time (called a “join” in SQL).

• Automatically access a subset of rows and columns in its underlying table(s), rather than always returning all rows and columns.

Note: TIBQuery is of particular importance to the development of scaleable database applications. If there is any chance that an application built to run against local databases will be scaled to a remote SQL database server in the future, use TIBQuery components from the start to ensure easier scaling later.

Properties Description

Transaction Identifies the transaction under which the query executes.

Params property Params: TParams;

Access Params at runtime to view and set parameter names, values, and data types dynamically (at design time use the collection editor for the Params property to set parameter information). Params is a zero-based array of TParams parameter records. Index specifies the array element to access.

Note: An easier way to set and retrieve parameter values when the name of each parameter is known is to call ParamByName. ParamByName cannot, however, be used to change a parameter’s data type or name.

Prepared property Prepared: Boolean;

Examine Prepared to determine if a query is already prepared for execution. If Prepared is True, the query is prepared, and if Prepared is False, the query is not prepared. While a query need not be prepared before execution, execution performance is enhanced if the query is prepared beforehand, particularly if it is a parameterized query that is executed more than once using the same parameter values.

Note: An application can change the current setting of Prepared to prepare or unprepare a query. If Prepared is True, setting it to False calls the Unprepare method to unprepare the query. If Prepared is False, setting it to True calls the Prepare method to prepare the query. Generally, however, it is better programming practice to call Prepare and Unprepare directly. These methods automatically update the Prepared property.

RowsAffected property RowsAffected: Integer;

Check RowsAffected to determine how many rows were updated or deleted by the last query operation. If RowsAffected is -1, the query did not update or delete any rows.

SQL property SQL: TStrings;

Use SQL to provide the SQL statement that a query component executes when its ExecSQL or Open method is called. At design time the SQL property can be edited by invoking the String List editor in the Object Inspector.

The SQL property may contain only one complete SQL statement at a time.

Methods Description

ExecSQL procedure ExecSQL;

Call ExecSQL to execute the SQL statement currently assigned to the SQL property. Use ExecSQL to execute queries that do not return a cursor to data (such as INSERT, UPDATE, DELETE, and CREATE TABLE).

Note: For SELECT statements, call Open instead of ExecSQL.

Page 57: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

53 DELPHI

ExecSQL prepares the statement in SQL property for execution if it has not already been prepared. To speed performance, an application should ordinarily call Prepare before calling ExecSQL for the first time.

ParamByName function ParamByName(const Value: string): TParam;

Call ParamByName to set or use parameter information for a specific parameter based on its name.

Value is the name of the parameter for which to retrieve information.

ParamByName is primarily used to set an parameter’s value at runtime.

Prepare procedure Prepare;

Call Prepare to have the remote database server allocate resources for the query and to perform additional optimizations. Calling Prepare before executing a query improves application performance.

Delphi automatically prepares a query if it is executed without first being prepared. After execution, Delphi unprepares the query. When a query will be executed a number of times, an application should always explicitly prepare the query to avoid multiple and unnecessary prepares and unprepares.

Preparing a query consumes some database resources, so it is good practice for an application to unprepare a query once it is done using it. The UnPrepare method unprepares a query.

Note: When you change the text of a query at runtime, the query is automatically closed and unprepared.

UnPrepare procedure UnPrepare;

Call UnPrepare to free the resources allocated for a previously prepared query on the server and client sides.

Preparing a query consumes some database resources, so it is good practice for an application to unprepare a query once it is done using it. The UnPrepare method unprepares a query.

Note: When you change the text of a query at runtime, the query is automatically closed and unprepared.

TIBDataSet TIBDataSet executes InterBase SQL statements.

Use TIBDataSet to execute InterBase SQL statements. Each TIBDataSet component has properties for a statement to fetch data (typically an SQL SELECT statement), a statement to modify those records, one for inserting records, one for deleting records, and one to refresh the dataset.

TIBDataSet buffers the result set, making it completely scrollable. Since TIBDataSet is a descendant of TDataSet, it works well with all data-aware components.

Properties Description

Transaction Identifies the transaction under which the query executes.

Database property Database: TIBDatabase;

Use Database to access the properties, events, and methods of the database component associated with this dataset.

DataSource property DataSource: TDataSource;

Use DataSource to get the data source of another dataset.

DeleteSQL property DeleteSQL: TStrings;

Holds the SQL statement used to delete rows from the dataset.

Use DeleteSQL to delete rows in the dataset.

InsertSQL property InsertSQL: TStrings;

Holds the SQL statement used to insert rows into the dataset.

Use InsertSQL to insert rows into the dataset.

SelectSQL property SelectSQL: TStrings;

Provides the ability to directly access the SQL object encapsulating the SelectSQL statement.

Use SelectSQL to access the SQL object that encapsulates the SelectSQL statement.

Params property Params: TIBXSQLDA;

Specifies the parameters to use for any parameterized queries.

Use Params to set up the parameters for the SQL object specified by the QSelect property. Params is the same as the SQLParams property.

ForcedRefresh property ForcedRefresh: Boolean;

Set ForcedRefresh to True to force the dataset to refresh its data every time it posts a record. When ForcedRefresh is False (the default), the data is only refreshed when you call the Refresh method, or when the dataset needs to fetch the value of a default or internally calculated field.

Methods Description

ExecSQL procedure ExecSQL;

Executes the SQL statement that the SelectSQL property specifies when it is not a SELECT statement.

Call ExecSQL to execute the main query for this dataset when it is not a SELECT statement. If the value of the SelectSQL property is not set, or if it is set to a SELECT statement, ExecSQL raises an

Page 58: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

54 DELPHI

EIBError exception.

ParamByName function ParamByName(Idx : String) : TIBXSQLVAR;

Returns a specified parameter of the SELECT query that fetches this dataset’s data.

Call ParamByName to retrieve the object that represents a parameter of the query that fetches this dataset’s data. Use the TIBXSQLVar object this method returns to get or set the parameter value.

Idx is the name of the parameter.

Prepare procedure Prepare;

Prepares all queries in the dataset to be executed.

Call Prepare to prepare all queries in the dataset to be executed.

UnPrepare procedure UnPrepare;

Resets the state of a dataset’s internal queries.

Call UnPrepare to reset the state of a dataset’s internal queries.

Page 59: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

55 HTML

Principali tag HTML

Elementi di base Tag Significato Note <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> tipo documento va posto prima di <HTML>

<HTML></HTML> documento HTML all'inizio e alla fine del file <TITLE></TITLE> titolo deve essere nella testata

<HEAD></HEAD> testata informazioni descrittive (ad es. il titolo)

<BODY></BODY> corpo contenuto della pagina

Sfondi e colori Tag Significato Note <BODY BACKGROUND="URL"> immagine di sfondo <BODY BGPROPERTIES="FIXED"> fissa senza scorrimento verticale <BODY BGCOLOR="#$$$$$$"> colore di sfondo <BODY TEXT="#$$$$$$"> del testo <BODY LINK="#$$$$$$"> dei collegamenti <BODY VLINK="#$$$$$$"> dei collegamenti visitati <BODY ALINK="#$$$$$$"> del collegamento selezionato

i colori possono essere specificati come codici RGB oppure con stringhe descrittive

Principali colori

Black = “#000000” Maroon = “#800000” Green = “#008000” Navy = “#000080”

Silver = “#C0C0C0” Red = “#FF0000” Lime = “#00FF00” Blue = “#0000FF”

Gray = “#808080” Purple = “#800080” Olive = “#808000” Teal = “#008080”

White = “#FFFFFF” Fuchsia = “#FF00FF” Yellow = “#FFFF00” Aqua = “#00FFFF”

Caratteri speciali Tag Significato Note &#?; carattere speciale ? indica il codice ISO 8859-1 &lt; < &gt; > &amp; & &quot; " &egrave; è &Egrave; È &eacute; é

analoghe rappresentazioni per le altre vocali a, o, i, u

&reg; marchio registrato TM (in alternativa &#174;) &copy; copyright (in alternativa &#169;) &nbsp; spazio da mantenere

Struttura Tag Significato Note

<H?></H?> titoli sono definiti 6 livelli (dal più grande H1 al più piccolo H6)

<H? ALIGN= LEFT|CENTER|RIGHT> </H?> allineamento titolo

<DIV></DIV> divisione di blocco usato per porzioni di testo o paragrafi

Page 60: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

56 HTML

<DIV ALIGN=LEFT|RIGHT| CENTER|JUSTIFY></DIV> allinemento del blocco

<SPAN></SPAN> divisione di blocco come DIV ma solitamente usato per brevi testi

<EM></EM> evidenziato in genere visualizzato in corsivo <STRONG></STRONG> molto evidenziato in genere visualizzato in neretto <CITE></CITE> citazione in genere visualizzato in corsivo <CODE></CODE> codice per listati di programmazione

<ADDRESS></ADDRESS> indirizzo dell'autore posto solitamente alla fine (vi si inserisce un riferimento dell’autore)

<BIG></BIG> font molto grande <SMALL></SMALL> font molto piccolo

Formattazione del testo Tag Significato Note <B></B> grassetto (bold) <I></I> corsivo (italic) <U></U> sottolineato (underline) <S></S> barrato (strikeout) <STRIKE></STRIKE> barrato (strikeout) alternativo a <S> <SUB></SUB> pedice <SUP></SUP> apice <TT></TT> font non scalabile visualizzato a spaziatura fissa

<PRE></PRE> preformattato visualizzato tale e quale; mantiene cioè gli allineamenti originali del testo

<PRE WIDTH=?></PRE> larghezza larghezza in caratteri <CENTER></CENTER> centrato sia per testo che immagini <FONT SIZE=?></FONT> grandezza del font valori da 1 a 7 <FONT SIZE=+?></FONT> <FONT SIZE=-?></FONT> grandezza del font

aumenta (+) o diminuisce (-) la grandezza del font

<BASEFONT SIZE=?> grandezza font di base da 1 a 7; valore di default 3 <FONT COLOR="#$$$$$$"></FONT> colore del font

<FONT FACE="***"></FONT> tipo font *** indica il nome del font (es. arial, serif, ...)

<BLINK></BLINK> lampeggiante supportato da Netscape <MARQUEE></MARQUEE> testo scorrevole supportato da MS

Collegamenti ed immagini Tag Significato Note <A HREF="URL"></A> collegamento di base in un altro documento <A HREF="URL#***"></A> link ad un’ancora in un altro file <A HREF="#***"></A> link ad un’ancora nello stesso file

<A HREF="URL" TARGET="***"></A> collegamento indicando la destinazione

l’url indicato viene visualizzato su una nuova finestra il cui nome è definito con target

<A NAME="***"></A> definizione di ancora nel file <A HREF="mailto:@"></A> indirizzo email <IMG SRC="URL"> inserimento immagine <IMG SRC="URL" ALIGN=TOP|BOTTOM |MIDDLE|LEFT|RIGHT> allineamento immagine

<IMG SRC="URL" ALT="***"> testo in alternativa se l'immagine non viene visualizzata

<IMG SRC="URL" WIDTH=? HEIGHT=?> dimensioni immagine in pixel

<IMG SRC="URL" WIDTH=% HEIGHT=%> dimensioni immagine

in percentuale della larghezza e altezza della pagina

<IMG SRC="URL" BORDER=?> bordo immagine in pixel

Page 61: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

57 HTML

<IMG SRC="URL" HSPACE=? VSPACE=?> spazio perimetrale immagine in pixel

<IMG SRC="URL" ISMAP> mappa navigabile richiede uno script <IMG SRC="URL" USEMAP="URL"> descrive una mappa descrizione della mappa <MAP NAME="***"></MAP> definizione della mappa <AREA SHAPE="DEFAULT|RECT| CIRCLE|POLY" COORDS="x,y,z" HREF="URL"|NOHREF>

sezione mappa nello stesso documento

Segni di paragrafo e separatori Tag Significato Note

<P></P> paragrafo spesso il comando di chiusura viene omesso

<P ALIGN=LEFT|CENTER|RIGHT></P> allineamento Netscape supporta anche ALIGN=JUSTIFY

<BR> interruzione riga singolo ritorno a capo <HR> riga orizzontale <HR ALIGN=LEFT| RIGHT|CENTER> allineamento riga orizzontale

<HR SIZE=?> spessore riga orizzontale in pixel

<HR WIDTH=?|”%”> larghezza riga orizzontale in pixel o come percentuale rispetto alla larghezza della pagina

<HR NOSHADE> piena senza l'effetto 3D

Liste Tag Significato Note <UL><LI></UL> liste senza ordine <LI> prima di ogni elemento <UL COMPACT></UL> lista compatta <UL TYPE=DISC|CIRCLE|SQUARE> tipo di puntatore valido per tutta la lista <LI TYPE=DISC|CIRCLE|SQUARE> tipo di puntatore valido per questo e i successivi <OL><LI></OL> lista numerata <LI> prima di ogni elemento <OL COMPACT></OL> lista compatta <OL TYPE=A|a|I|i|1> tipo di numero valido per tutta la lista <LI TYPE=A|a|I|i|1> tipo di numero valido per questo e i successivi <OL VALUE=?> numero di partenza valido per tutta la lista <LI VALUE=?> numero di partenza per questo e i successivi

<DL><DT><DD></DL> lista di definizioni <DT>=termine, <DD>=definizione

<DL COMPACT></DL> lista compatta

Tabelle Tag Significato Note <TABLE></TABLE> definizione tabella <TABLE ALIGN=LEFT| RIGHT|CENTER> allineamento tabella

<TABLE BORDER> </TABLE> bordo per visualizzare il bordo

<TABLE BORDER=?> </TABLE> spessore bordo valore in pixel

<TABLE CELLSPACING=?> spazio tra celle

<TABLE CELLPADDING=?> spazio nella cella spazio tra il testo e il bordo della cella

<TABLE WIDTH=?> larghezza tabella in pixel

<TABLE WIDTH=%> larghezza % in percentuale rispetto alla pagina

<TABLE BGCOLOR="#$$$$$$"> colore sfondo

Page 62: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

58 HTML

</TABLE> <TABLE BORDERCOLOR="#$$$$$$"> </TABLE> colore bordo

<TABLE BORDERCOLORDARK="#$$$$$$"> </TABLE>

colore scuro

<TABLE BORDERCOLORLIGHT="#$$$$$$"> </TABLE>

colore chiaro

<TR></TR> riga <TR ALIGN=LEFT|RIGHT| CENTER|MIDDLE|BOTTOM> allineamento riga

<TD></TD> colonna deve essere all'interno di una definizione di riga

<TD ALIGN=LEFT|RIGHT|CENTER VALIGN=TOP|MIDDLE|BOTTOM>

allineamento orizzontale e verticale

<TD NOWRAP> senza interruzione

<TD COLSPAN=?> unione colonne ? è il numero di colonne da occupare

<TD ROWSPAN=?> unione righe ? è il numero di righe da occupare

<TD WIDTH=?> larghezza colonna in pixel

<TD WIDTH="%"> larghezza colonna % valore in percentuale della larghezza della tabella

<TD BGCOLOR="#$$$$$$"> colore di sfondo della cella

<TH></TH> titolo della colonna come <TD> ma in neretto e centrata

<TH ALIGN=LEFT|RIGHT| CENTER|MIDDLE|BOTTOM> allineamento

<TH NOWRAP> senza interruzione <TH COLSPAN=?> unione colonne <TH ROWSPAN=?> unione righe <TH WIDTH=?> larghezza <TH WIDTH="%"> larghezza % <TH BGCOLOR="#$$$$$$"> colore di sfondo della cella

<CAPTION></CAPTION> legenda della tabella visualizzata in testa alla tabella (centrata sulla larghezza e fuori dall’eventuale bordo)

<CAPTION ALIGN=TOP|BOTTOM| LEFT|RIGHT> allineamento legenda

posizione rispetto alla tabella (sopra o sotto, sopra a sinistra, sopra a destra)

Moduli Tag Significato Note <FORM ACTION="URL" METHOD=GET|POST> </FORM>

definizione

<FORM ENCTYPE="multipart/form-data"></FORM> upload di file

<INPUT TYPE="TEXT|PASSWORD| CHECKBOX|RADIO|FILE|BUTTON| IMAGE|HIDDEN|SUBMIT|RESET">

campo di immissione

<INPUT NAME="***"> nome del campo <INPUT VALUE="***"> valore di default <INPUT MAXLENGTH=?> lunghezza massima in caratteri <INPUT CHECKED> selezionato di default checkbox e radio <INPUT SIZE=?> misura in caratteri <SELECT></SELECT> lista selezione da un elenco di opzioni <SELECT NAME="***"></SELECT> nome campo <SELECT SIZE=?></SELECT> numero opzioni

<SELECT MULTIPLE> selezione multipla per selezionare più di un elemento

Page 63: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

59 HTML

<OPTION> opzioni elementi che possono essere selezionati

<OPTION SELECTED> opzione selezionata

<OPTION VALUE="***"> valore label visualizzata accanto all’opzione

<OPTGROUP LABEL="***"> </OPTGROUP> gruppo di opzioni

<TEXTAREA ROWS=? COLS=?></TEXTAREA> area di immissione testo

<TEXTAREA NAME="***"></TEXTAREA> nome dell’area

<TEXTAREA WRAP=OFF|HARD|SOFT></TEXTAREA>

a capo automatico in diversi modi

Frame Tag Significato Note <FRAMESET></FRAMESET> documento frame al posto di <BODY> <FRAMESET ROWS=,,,> </FRAMESET>

altezza in righe pixel o percentuale

<FRAMESET ROWS=*></FRAMESET> altezza in righe * misura relativa <FRAMESET COLS=,,,></FRAMESET> larghezza in colonne pixel o percentuale <FRAMESET COLS=*></FRAMESET> larghezza in colonne * misura relativa <FRAMESET FRAMEBORDER="yes|no"> </FRAMESET>

cornice

<FRAME> definizione frame contenuto di ogni singolo quadro <FRAME SRC="URL"> visualizza documento <FRAME NAME="***"|_blank|_self|_parent|_top>

nome del frame

<FRAME MARGINWIDTH=?> larghezza margine margine destro o sinistro <FRAME MARGINHEIGHT=?> altezza margine margine alto o basso <FRAME SCROLLING="YES|NO|AUTO"> barra di scorrimento <FRAME NORESIZE> misure non modificabili

<NOFRAMES></NOFRAMES> contenuto in assenza di frame per i browser che non supportano frame

Page 64: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

60 Sistemi

ComPort

Use TComPort component to easily communicate with external devices on RS232 connection, such as modems, bar code readers, PBX and so on. TCustomComPort introduces several properties for detailed setting of serial port, numerous methods to write and read from port and events for monitoring port. Write and read operations can be performed synchronously or asynchronously.

Properties

Cport.Connected

Set Connected to True to open serial port. Set Connected to False close connection to serial port. An application can check Connected to determine whether or not a serial port is open. If Connected is True, serial port is open, otherwise it is closed.

CPort.Buffer Use Buffer property to set the size of input and output buffer of serial port.

CPort.BaudRate

BaudRate property represents the speed at which charchters are sent or received via RS232 conection. Both sides of connection should have the same BaudRate. If BaudRate has a value of brCustom, CustomBaudRate property is used to set baud rate.

Methods: Lettura e scrittura

CPort.ReadStr(r,Count) Call ReadStr function to read Count bytes into Str variable. The function does not return until Count bytes are read or timeout elapses.

The return value is the number of bytes that are actually read.

CPort.WriteStr(s) Call WriteStr function to write Str variable to output buffer. The function does not return until whole string is written or timeout elapses.

The return value is the number of bytes that are actually written.

Cport.Close Close method closes connection to serial port. If serial port is already closed, Close method does nothing. When port is closed, application can't read or write to it.

Cport.Open Open method connects to a serial port and sets all port settings defined in TCustomComPort properties. If a port is already opened, nothing happen

Eventi

OnRxchar

Write OnRxChar event handler to get information about recently arrived charachters in input buffer. Count parameter is the number of bytes in input buffer waiting to be read. OnRxChar event is usually used for reading charachters from input buffer.

OnRxBuf

Write OnRxChar event handler to get data that had arrived in input buffer, but it has already been read from it by other linked component such as TComDataPacket or TCustomComTerminal. The application can not read the data from input buffer, because it has already been read from it and placed in Buffer parameter.

OnBreak Write OnBreak event handler to take specific action when hardware detects a break on input.

OnError Write OnError event handler to take specific action when a line status error occurs. Line status errors are ceFrame, ceOverrun, ceRxParity

OnAfterClose Write OnAfterClose event handler to take specific action after serial port is successfully closed using Close method or Connected property. If closing of serial port fails, OnAfterClose event is not triggered.

OnAfterOpen Write OnAfterOpen event handler to take specific action after serial port is successfully opened using Open method or Connected property. If opening of serial port fails, OnAfterOpen event is not triggered.

Page 65: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

61 Sistemi

Componenti SOCKET

Properties Description

Active Property Active: Boolean;

Indicates whether the socket connection is open and available for communication with other machines.

Before attempting to use or change the socket connection, read Active to determine whether the connection is open and ready. For client sockets, setting Active opens or shuts down a socket connection to another machine. For server sockets, setting Active opens or shuts down a listening connection that makes the socket available for client requests.

At design time, set Active to True to make the socket open a connection when the application starts running. At runtime, use the Open or Close method to open or close the connection.

Address Property Address: string;

Address is a string of four numeric (byte) values in the standard Internet dot notation, such as

123.197.1.2

For client sockets, set Address to the IP address of the server to which the socket should connect. When the connection is opened, the value of Address is bound to the connection.

If the socket specifies the Host property, the address for the connection is taken from the IP address associated with Host, rather than the value of Address. Specifying the server system by giving the IP address is faster, because the socket doesn’t need to search for the IP address associated with the host name before it can locate the server system.

A single system may support more than one IP address.

Note: Trying to change Address when the connection is open will raise an ESocketError exception.

Host Property Host: string;

Host is a string containing the domain name and service of a particular system, such as

http:\\www.google.it

For client sockets, set Host to the system with which the client socket should form a connection. When the socket opens a connection, it looks up the IP address for the server socket using the value of Host.

Some servers change the system or IP address that is associated with a particular host name. Using a host name allows the client socket to find the abstract site represented by the host name, even when it has moved to a new IP address.

If Host is set, it takes precedence over the Address property when looking up the address of the server.

Note: Trying to change Host when the connection is open will raise an ESocketError exception.

Port Property Port: Integer;

Port numbers allow a single system, identified by the Host or Address property, to host multiple connections simultaneously. Many values of Port are associated by convention with a particular service such as ftp or http.

For server sockets, Port is the ID of the connection on which the server socket listens for client requests. Server sockets generally set Port to a predefined value which clients can use to initiate connections.

For client sockets, Port is the ID of the desired server connection. The value of Port is usually associated with the service the client wishes to use on the server application.

Note: Trying to change Port when the connection is open will raise an ESocketError exception.

Service

Property Service: string;

Use Service to identify the use of the connection. Windows provides a number of standard service names such as ftp, http, finger, and time. Servers can specify additional services and their associated ports in a SERVICES file. For more information, see the Microsoft documentation for Windows sockets.

Page 66: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

62 Sistemi

Certain port numbers are reserved for specific values of service. Thus, Service provides a more meaningful way to specify the server Port to use for the socket connection. For server sockets, using Service rather than Port ensures that the server will listen for TCP/IP requests on the appropriate port.

Note: Trying to change Service when the connection is open will raise an ESocketError exception.

Methods Description

Close Procedure Close;

Call Close to shut down the socket connection. Close sets the Active property to False.

For client sockets, Close terminates the connection to the server. For server sockets, Close shuts down the connection so that the server socket is no longer listening for client requests.

Open Procedure Open;

Call Open to initiate the socket connection. Open sets the Active property to True.

For client sockets, Open locates and connects to a server. For server sockets, Open opens the socket connection in a listening mode, but does not complete the connection to a client socket.

TClientSocket Add a TClientSocket object to a form or data module to turn an application into a TCP/IP client. TClientSocket specifies a desired connection to a TCP/IP server, manages the connection when it is open, and terminates the connection when the application is through.

Use Socket to

Determine the address and port of both the client and server sockets that are bound to the connection.

_Read or write information through the socket connection.

_Determine what server notifications the client will respond to.

_iObtain the Windows socket handle for making Windows socket API calls.

Events Description

OnConnect Property OnConnect: TSocketNotifyEvent;

Write an OnConnect event handler for a client socket to take specific action after the connection to a server socket has been established. Depending on the service, this may be the point when the socket should start reading or writing over the connection. When a client socket opens a connection, the following events occur:

1 An OnLookup event occurs prior to an attempt to locate the server socket.

2 The Windows socket is set up, and initialized for event notification.

3 An OnConnecting event occurs after the server socket is located.

4 The connection request is accepted by the server and completed by the client socket.

5 An OnConnect event occurs after the connection is established.

OnConnecting Property OnConnecting: TSocketNotifyEvent;

Write an OnConnecting event handler for a client socket to take specific action just before the connection to a server socket is established. This is the first opportunity to obtain the actual port and IP address of the server endpoint of the connection that is about to form.

When a client socket opens a connection, the following events occur:

1 An OnLookup event occurs prior to an attempt to locate the server socket.

2 The Windows socket is set up, and initialized for event notification.

3 An OnConnecting event occurs after the server socket is located.

4 The connection request is accepted by the server and completed by the client socket.

5 An OnConnect event occurs after the connection is established.

Page 67: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

63 Sistemi

OnDisconnect Property OnDisconnect: TSocketNotifyEvent;

Write an OnDisconnect event handler to take specific action when the connection to a server socket is about to be terminated. OnDisconnect occurs after the value of the Active property is set to False, but before the actual connection is closed.

OnError Property OnError: TSocketErrorEvent;

Write an OnError event handler to respond to errors that arise with the socket connection. Set the ErrorCode parameter to 0 if the OnError event handler successfully deals with the error condition, to prevent an ESocketError from being raised.

OnLookup Property OnLookup: TSocketNotifyEvent;

Write an OnLookup event handler for a client socket to take specific action just before attempting to locate a server socket. This is the first opportunity to make Windows API calls that affect the client properties of the socket, such as specifying a particular port number. Use the SocketHandle property of the Socket parameter for Windows API calls.

When a client socket opens a connection, the following events occur:

1 An OnLookup event occurs prior to an attempt to locate the server socket.

2 The Windows socket is set up, and initialized for event notification.

3 An OnConnecting event occurs after the server socket is located.

4 The connection request is accepted by the server and completed by the client socket.

5 An OnConnect event occurs after the connection is established.

Note: Changing the Address, Host, Port, or Service properties of socket component in an OnLookup event handler has no effect on the address or port used to locate a server socket. These properties must be correct before the Open method is called.

OnWrite Property OnWrite: TSocketNotifyEvent;

Write an OnWrite to write from the socket connection. If the socket is a blocking socket, use a TwinSocketStream object to write to the connection. Otherwise, use the methods of the Socket parameter to perform the actual writing.

OnRead Property OnRead: TSocketNotifyEvent;

Write an OnRead event handler to read from the socket connection. If the socket is a blocking socket, use a TWinSocketStream object to read from the connection. Otherwise, use the methods of the Socket parameter to perform the actual reading.

Note: Non-blocking sockets do not always receive an OnRead event for the last bit of data passed over the connection. When using a non-blocking socket, check for any unread data in the OnDisconnect event to make sure that everything is handled.

Page 68: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

64 Sistemi

TServerSocket TServerSocket manages server socket connections for a TCP/IP server.

Unit: ScktComp

Add a TServerSocket object to a form or data module to turn an application into a TCP/IP server. TServerSocket listens for requests for TCP/IP connections from other machines, and establishes connections when requests are received.

Events Description

OnClientConnect property OnClientConnect: TSocketNotifyEvent;

Occurs when a client socket completes a connection accepted by the server socket.

Write an OnClientConnect event handler to take specific action when a client socket completes the socket connection to the server socket. For example, the socket may start reading or writing over the connection in an OnClientConnect event handler.

The order of server socket events leading up to OnClientConnect is as follows:

1 An OnListen event occurs just before the server socket is opened for listening.

2 The server socket receives client requests in a listening queue. The server socket accepts one of those requests, and receives a Windows socket handle for the new socket connection.

3 The server socket generates an OnGetSocket event, passing in the Windows socket handle. If a TserverClientWinSocket object for the server endpoint of the new connection is not created in an OnGetSocket event handler, the server socket creates one. The TServerWinSocket object continues to listen for other clients.

4 An OnAccept event occurs, using the new TServerClientWinSocket object.

5 If ServerType is stThreadBlocking and no thread is available in the cache, an OnGetThread event occurs. If the OnGetThread event handler does not create a thread, the server socket creates a TServerClientThread.

6 If ServerType is stThreadBlocking, an OnThreadStart event occurs as the thread begins execution.

7 The client completes the connection to the TServerClientWinSocket object and an OnClientConnect event occurs.

Note: If ServerType is stThreadBlocking, make sure that all code in an OnClientConnect event handler is thread-safe. Use the GetClientThread method of the Sender parameter to access thread-specific information.

Note: The OnClientConnect event handler for TServerSocket is also set when setting the OnClientConnect event handler of the associated TServerWinSocket.

OnClientDisconnect property OnClientDisconnect: TSocketNotifyEvent;

Occurs when one of the connections to a client socket is closed.

Write an OnClientDisconnect event handler to take specific action when the connection to a client socket is ending. The termination of a client connection does not close the server socket. The server socket remains open and listening for client requests on its listening connection.

The TServerClientWinSocket that describes the server endpoint of the client connection is freed after OnClientDisconnect. If ServerType is stThreadBlocking, OnThreadEnd occurs after OnClientDisconnect.

Note: If ServerType is stThreadBlocking, make sure that all code in an OnClientDisconnect event handler is thread-safe. Use the GetClientThread method of the Sender parameter to access thread-specific information.

Note: The OnClientDisconnect event handler for TServerSocket is also set when setting the OnClientDisconnect event handler of the associated TServerWinSocket.

OnClientError property OnClientError: TSocketErrorEvent;

Occurs when there is a failure in establishing, using, or terminating the socket connection to an individual client socket.

Page 69: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

65 Sistemi

Write an OnClientError event handler to respond to errors that arise with a connection to an individual client. Set the ErrorCode parameter to 0 if the OnClientError event handler successfully deals with the error condition to prevent an ESocketError from being raised.

Note: If ServerType is stThreadBlocking, make sure that all code in an OnClientError event handler is thread-safe. Use the GetClientThread method of the Sender parameter to access thread-specific information.

Note: The OnClientError event handler for TServerSocket is also set when setting the OnClientError event handler of the associated TServerWinSocket.

OnClientRead property OnClientRead: TSocketNotifyEvent;

Occurs when the server socket should read information from a client socket.

Write an OnClientWrite event handler to write to the socket connection. If the ServerType property is stThreadBlocking, use a TWinSocketStream object to prevent problems that arise while writing from causing the execution thread to hang indefinitely. Otherwise, use the methods of the Socket parameter to perform the actual writing.

Note: If ServerType is stThreadBlocking, make sure that all code in an OnClientRead event handler is thread-safe. Use the GetClientThread method of the Sender parameter to access thread-specific information.

OnClientWrite property OnClientWrite: TSocketNotifyEvent;

Occurs when the server socket should write information to a client socket.

Write an OnClientWrite event handler to write to the socket connection. If the ServerType property is stThreadBlocking, use a TWinSocketStream object to prevent problems that arise while writing from causing the execution thread to hang indefinitely. Otherwise, use the methods of the Socket parameter to perform the actual writing.

Note: If ServerType is stThreadBlocking, make sure that all code in an OnClientWrite event handler is thread-safe. Use the GetClientThread method of the Sender parameter to access thread-specific information.

OnAccept property OnAccept: TSocketNotifyEvent;

Occurs on server sockets just after the connection to a client socket is accepted.

Write an OnAccept event handler for a server socket to take specific action after the connection to a client socket has been accepted. This is the first point when information is available about the local port and IP address that will be used in the server endpoint of the connection. The port number, and possibly the IP address, will differ from those of the listening socket.

Server sockets open a socket connection for listening to establish a queue to hold client requests. After a request from the queue is accepted by the server socket, an OnAccept event occurs. After the server socket accepts the connection, the client socket completes the connection, and an OnConnect event occurs for the client socket.

OnListen property OnListen: TSocketNotifyEvent;

Occurs just before a server socket is opened for listening.

Write an OnListen event handler for a server socket to take specific action just before the socket is opened for listening. OnListen occurs after Address and Port have been bound to the socket connection, but before it is opened. This is the last opportunity to make changes to the socket endpoint before it is opened for listening. Use the SocketHandle property of the Socket parameter for Windows API calls that change the socket.

Server sockets open a socket connection for listening to establish a queue to hold client requests. The connection to a client socket is completed when a request from the queue is accepted.

Page 70: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

66 Sistemi

XML

Struttura documento XML <?xml version=”1.0” encoding=”UTF-8”?> <NomeTag> <NomeTag2>Valore</NomeTag2> </NomeTag>

Schema di validità documento XML <!DOCTYPE NomeTag [ <!ELEMENT NomeTag (NomeTag2)> <!ELEMENT NomeTag2 (#PCDATA)> ]>

Componente TXMLDocument Proprieties Description

AddChild(TagName:string) Aggiunge un nuovo nodo figlio al documento

ChildNode(Index:Integer) Raggiuge ogni nodo figlio all’interno del documento

ChildValue(TagName:string) Specifica il nome del nodo

XML Legge il documento XML

XML.Text Vado a scrivere sul documento XML

Active(:Boolean) Attivo l’oggetto

Method Description

ChildNode(Index:Integer) Raggiuge ogni nodo figlio all’interno del documento

ChildValue(TagName:string) Specifica il nome del nodo

XML Legge il documento XML

XML.Text Vado a scrivere sul documento XML

Active(:Boolean) Attivo l’oggetto

Page 71: SQL PHP Delphi HTML XML - Istituto Guglielmo  · PDF fileSQL PHP Delphi HTML XML ... Componenti data-aware Delphi ... ComPort .....60 Componenti SOCKET

67 Sistemi

Componente IOPort

TIOPort provides properties for reading and writing bytes, words and doublewords from/to IO ports

Properties Description

Port[Index: Dword]: Byte; Use this property for reading or writing a byte from/to IO port. Index specifies the IO port used for reading or writing.

Simbologia LAN

Bridge

Firewall

W orkstation

Router

ATM Switch

PrinterPhone

Hub

Laptop