PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<posix_unamepg_affected_rows>
view the version of this page
Last updated: Sun, 02 May 2004

LXXXIV. Funzioni PostgreSQL

Introduzione

Il database PostgreSQL è un prodotto OpenSource ed è disponibile gratuitamente. Postgres, sviluppato originariamente nel Dipartimento di Informatica dell'Università di Berkeley, ha anticipato molti dei concetti su oggetti e relazioni che ora stanno diventando disponibili in alcuni database commerciali. Postgres fornisce supporto per il linguaggio SQL/92/SQL99, transazioni, integrità referenziale, stored procedures ed estensibilità dei tipi. PostgreSQL è un discendente open source dell'originario codice di Berkeley.

Requisiti

Per utilizzare il supporto a PostgreSQL, occorre PostgreSQL 6.5 o versioni più recenti. PostgreSQL 7.0 o successivi permettono di abilitare tutte le funzionalità di questo modulo. PostgreSQL ammette molte codifiche di carattere, tra cui la codifica multibyte. La versione corrente e maggiori informazioni su PostgreSQL sono disponibili su http://www.postgresql.org/ e http://techdocs.postgresql.org/.

Installazione

In order to enable PostgreSQL support, --with-pgsql[=DIR] is required when you compile PHP. DIR is the PostgreSQL base install directory, defaults to /usr/local/pgsql. If shared object module is available, PostgreSQL module may be loaded using extension directive in php.ini or dl() function.

Configurazione di Runtime

Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.

Tabella 1. PostgreSQL configuration options

NameDefaultChangeable
pgsql.allow_persistent"1"PHP_INI_SYSTEM
pgsql.max_persistent"-1"PHP_INI_SYSTEM
pgsql.max_links"-1"PHP_INI_SYSTEM
pgsql.auto_reset_persistent"0"PHP_INI_SYSTEM
pgsql.ignore_notice"0"PHP_INI_ALL
pgsql.log_notice"0"PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Breve descrizione dei parametri di configurazione.

pgsql.allow_persistent boolean

Whether to allow persistent Postgres connections.

pgsql.max_persistent integer

The maximum number of persistent Postgres connections per process.

pgsql.max_links integer

The maximum number of Postgres connections per process, including persistent connections.

pgsql.auto_reset_persistent integer

Detect broken persistent links with pg_pconnect(). Needs a little overhead.

pgsql.ignore_notice integer

Whether or not to ignore PostgreSQL backend notices.

pgsql.log_notice integer

Whether or not to log PostgreSQL backends notice messages. The PHP directive pgsql.ignore_notice must be off in order to log notice messages.

Utilizzo e suggerimenti

Attenzione

L'utilizzo del modulo PostgreSQL con PHP 4.0.6 non è raccomandato a causa di un bug nella gestione dei messaggi. Si usi PHP 4.1.0 o successivi.

Attenzione

I nomi delle funzioni relative a PostgreSQL verranno cambiate a partire dalla versione 4.2.0 per conformarsi agli standard di sviluppo attuali. La maggior parte dei nuovi nomi avrà underscore aggiuntivi, per esempio pg_lo_open(). Alcune funzioni verranno rinominate per dare consistenza. Per esempio pg_exec() diventerà pg_query(). I vecchi nomi potranno essere usati nella versione 4.2.0 e in alcune versioni successive alla 4.2.0, ma potranno essere cancellati in futuro.

Tabella 2. Nomi di funzione cambiati

Vecchio nomeNuovo nome
pg_exec()pg_query()
pg_getlastoid()pg_last_oid()
pg_cmdtuples()pg_affected_rows()
pg_numrows()pg_num_rows()
pg_numfields()pg_num_fields()
pg_fieldname()pg_field_name()
pg_fieldsize()pg_field_size()
pg_fieldnum()pg_field_num()
pg_fieldprtlen()pg_field_prtlen()
pg_fieldisnull()pg_field_is_null()
pg_freeresult()pg_free_result()
pg_result()pg_fetch_result()
pg_loreadall()pg_lo_read_all()
pg_locreate()pg_lo_create()
pg_lounlink()pg_lo_unlink()
pg_loopen()pg_lo_open()
pg_loclose()pg_lo_close()
pg_loread()pg_lo_read()
pg_lowrite()pg_lo_write()
pg_loimport()pg_lo_import()
pg_loexport()pg_lo_export()

La vecchia sintassi di pg_connect()/pg_pconnect() sarà deprecata per supportare, in futuro, connessioni asincrone. Si usi una stringa di connessione con pg_connect() e pg_pconnect().

Non tutte le funzioni sono supportate su tutte le architetture. Dipende dalla versione di libpq (L'interfaccia Client C per PostgreSQL) e da come libpq è compilato. Se c'è una funzione mancante, libpq non supporta la feature richiesta per quella funzione.

È importante usare versioni di libpq più recenti rispetto al Server PostgreSQL al quale ci si vuole collegare. Se si usa una versione di libpq più vecchia rispetto al Server PostgreSQL al quale ci si vuole collegare, si andrà probabilmente incontro a problemi.

Fin dalla versione 6.3 (03/02/1998) PostgreSQL usa gli unix domain socket di default. La porta TCP, di default, NON verrà aperta. La tabella sottostante descrive queste nuove possibilità di connessione. Questo socket può essere trovato in /tmp/.s.PGSQL.5432. Questa opzione può venire abilitata con la flag '-i' da postmaster e il suo significato è: "ascolta i socket TCP/IP così come gli Unix domain socket".

Tabella 3. Postmaster e PHP

PostmasterPHPStatus
postmaster &pg_connect("dbname=NomeMioDatabase");OK
postmaster -i &pg_connect("dbname=NomeMioDatabase");OK
postmaster &pg_connect("host=localhost dbname=NomeMioDatabase"); Unable to connect to PostgreSQL server: connectDB() failed: Is the postmaster running and accepting TCP/IP (with -i) connection at 'localhost' on port '5432'? in /path/to/file.php on line 20.
postmaster -i &pg_connect("host=localhost dbname=NomeMioDatabase");OK

Si può stabilire una connessione al server PostgreSQL usando le seguenti coppie di valori impostate nella stringa di comando: $conn = pg_connect("host=IlMioHost port=LaMiaPorta tty=myTTY options=LeMieOpzioni dbname=IlMioDB user=IlMioUtente password=LaMiaPassword ");

L'uso della sintassi in uso precedentemente: $conn = pg_connect ("host", "port", "options", "tty", "dbname") è deprecato.

Le variabili d'ambiente modificano il comportamento server/client di PostgreSQL. Per esempio, il modulo PostgreSQL si baserà sulla variabile PGHOST quando il nome dell'host è omesso nella stringa di connessione. Le variabili d'ambiente riconosciute sono diverse da versione a versione. Consultare il Manuale del Programmatore PostgreSQL (libpq - Variabili d'Ambiente) per ulteriori dettagli.

Assicurarsi di aver impostato le variabili d'ambiente per l'utente appropriato. Usare $_ENV o getenv() per controllare quali variabili d'ambiente sono disponibili al processo corrente.

Esempio 1. Impostazione dei parametri di default

PGHOST=pgsql.example.com
PGPORT=7890
PGDATABASE=web-system
PGUSER=web-user
PGPASSWORD=segreta
PGDATESTYLE=ISO
PGTZ=JST
PGCLIENTENCODING=EUC-JP

export PGHOST PGPORT PGDATABASE PGUSER PGPASSWORD PGDATESTYLE PGTZ PGCLIENTENCODING

Costanti predefinite

Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.

PGSQL_ASSOC (integer)

PGSQL_NUM (integer)

PGSQL_BOTH (integer)

PGSQL_CONNECTION_BAD (integer)

PGSQL_CONNECTION_OK (integer)

PGSQL_SEEK_SET (integer)

PGSQL_SEEK_CUR (integer)

PGSQL_SEEK_END (integer)

PGSQL_ESCAPE_STRING (integer)

PGSQL_ESCAPE_BYTEA (integer)

PGSQL_EMPTY_QUERY (integer)

PGSQL_COMMAND_OK (integer)

PGSQL_TUPLES_OK (integer)

PGSQL_COPY_OUT (integer)

PGSQL_COPY_IN (integer)

PGSQL_BAD_RESPONSE (integer)

PGSQL_NONFATAL_ERROR (integer)

PGSQL_FATAL_ERROR (integer)

Esempi

A partire da PostgreSQL 7.1.0, il tipo di dato text ha 1GB come dimensione massima. Nelle versioni più vecchie di PostgreSQL il tipo di dato text è limitato dalla dimensione del block. (Default 8KB. Massimo 32KB, specificato al momento della compilazione)

Per usare l'interfaccia large object (lo), è necessario includerla entro un blocco di una transazione. Un blocco di transazione inizia con un comando SQL BEGIN e se la transazione è stata valida, termina con COMMIT o END. Se la transazione fallisce, essa deve venire chiusa con ROLLBACK o ABORT.

Esempio 2. Utilizzare Large Objects

<?php
   $database
= pg_connect ("dbname=jacarta");
  
pg_query ($database, "begin");
  
$oid = pg_lo_create ($database);
   echo
"$oid\n";
  
$handle = pg_lo_open ($database, $oid, "w");
   echo
"$handle\n";
  
pg_lo_write ($handle, "dati large object");
  
pg_lo_close ($handle);
  
pg_query ($database, "commit");
?>
Non chiudere la risorsa di connessione prima di aver chiuso la risorsa large object.

Sommario
pg_affected_rows -- Restituisce il numero delle tuple coinvolte dall'ultimo comando
pg_cancel_query --  Annulla una query asincrona
pg_client_encoding --  Restituisce la codifica caratteri del client
pg_close -- Chiude una connessione PostgreSQL
pg_connect -- Stabilisce una connessione PostgreSQL
pg_connection_busy --  Riferisce se una connessione è occupata o meno
pg_connection_reset --  Rpristina la connessione (riconnette)
pg_connection_status --  Restituisce lo stato di una connessione
pg_convert --  Converte i valori di un array associativo in una forma compatibile con i comandi SQL.
pg_copy_from --  Inserisce le tuple in una tabella prendendole da un array
pg_copy_to --  Copia una tabella in un array
pg_dbname -- Restituisce il nome del database
pg_delete --  Cancella le tuple.
pg_end_copy -- Esegue una sincronizzazione con il backend PostgreSQL
pg_escape_bytea --  Aggiunge le sequenze di escape ai dati binari nel tipo bytea
pg_escape_string --  Aggiunge le sequenze di escape nei tipi text/char
pg_fetch_all -- Carica tutte le tuple in un array
pg_fetch_array -- Carica una tupla in un array
pg_fetch_assoc -- Fetch a row as an array
pg_fetch_object -- Carica una tupla in un oggetto
pg_fetch_result -- Restituisce i valori da una risorsa di risultato
pg_fetch_row -- Carica una tupla in un array
pg_fieldisnull -- Verifica se un campo è NULL
pg_field_name -- Restituisce il nome di un campo
pg_field_num -- Restituisce la posizione del campo specificato
pg_field_prtlen -- Restituisce la lunghezza "stampabile" di un valore
pg_field_size --  Restituisce la reale dimensione di memorizzazione del campo
pg_field_type --  Restituisce il nome del tipo del campo specificato
pg_free_result -- Libera la memoria allocata per i risultati
pg_get_notify -- Ping database connection
pg_get_pid -- Ping database connection
pg_get_result --  Recupera i risultati di una query asincrona
pg_host --  Restituisce il nome dell'host associato alla connessione
pg_insert --  Inserisce un array in una tabella.
pg_last_error -- Restituisce l'ultimo messaggio d'errore di una connessione
pg_last_notice --  Restituisce l'ultimo messaggio di notifica dal server PostgreSQL
pg_last_oid -- Restituisce l'oid dell'ultimo oggetto
pg_lo_close -- Chiude un large object
pg_lo_create -- Crea un large object
pg_lo_export -- Esporta un large object salvandolo su un file
pg_lo_import -- Importa un large object da un file
pg_lo_open -- Apre un large object
pg_lo_read_all --  Legge interamente un large object e lo manda direttamente al browser
pg_lo_read -- Legge un large object
pg_lo_seek --  Ricerca la posizione di un large object
pg_lo_tell --  Restituisce la posizione attuale in un large object
pg_lo_unlink -- Cancella un large object
pg_lo_write -- Scrive un large object
pg_meta_data --  Ottiene la definizione di una tabella.
pg_num_fields -- Restituisce il numero di campi
pg_num_rows -- Restituiscein numero di tuple
pg_options -- Estrae le opzioni associate alla connessione
pg_pconnect -- Open a persistent PostgreSQL connection
pg_ping -- Ping database connection
pg_port --  Restituisce il numero di porta associato alla connessione
pg_put_line -- Invia una stringa terminata da NULL al backend PostgreSQL
pg_query -- Esegue una query
pg_result_error --  Restituisce i messaggio di errore associato al risultato
pg_result_seek -- Set internal row offset in result resource
pg_result_status --  Recupera lo stato del risultato di una query
pg_select --  Seleziona delle tuple.
pg_send_query --  Invia una query in modo asincrono
pg_set_client_encoding --  Imposta la codifica del client
pg_trace -- iAbilita il tracciamento di una connessione PostgreSQL
pg_tty --  Restituisce il nome della tty associata alla connessione
pg_unescape_bytea --  Escape binary for bytea type
pg_untrace -- Disabilita il tracciamento di una connessione PostgreSQL
pg_update --  Modifica le tuple della tabella


add a note add a note User Contributed Notes
Funzioni PostgreSQL
17-Mar-2004 11:50
I wrote some code that converts Postgres arrays to PHP arrays.  I haven't done too much testing, but it seems to do the job for me. 

/**
* A quick and dirty array grabber for postgres arrays.  Not
* tested very well.
* @returns A PHP array.
**/
function toArray($pgArray){
  if(strlen($pgArray) == 0){
   return;
  }
  elseif($this->getChar($pgArray) == "," or $this->getChar($pgArray) == " "){
   return $this->toArray(substr($pgArray, 1));
  }

  elseif($this->getChar($pgArray) == "{"){
   //find the end of the array
   $depth = 1;
   for($i=1; $depth>0 && $i<strlen($pgArray); $i++){
     if($this->getChar($pgArray, $i) == '\\'){
       //skip escape chars
       $i++;
       next;
     }
     if($this->getChar($pgArray, $i) == "{"){
       $depth++;
       next;
     }
     if($this->getChar($pgArray, $i) == "}"){
       $depth--;
       next;
     }
   }
   $arrayEnd = $i;
   $first = substr($pgArray, 1, $arrayEnd - 2);
   $second = substr($pgArray, $arrayEnd);
   if($second == ""){
     return $this->toArray($first);
   }
   $r[] = $this->toArray($first);
   $r[] = $this->toArray($second);
   return $r;
  }
      
  elseif($this->getChar($pgArray) == "\""){
   //a quoted item
   $depth = 1;
   for($i=1; $depth && $i<strlen($pgArray); $i++){
     if($this->getChar($pgArray, $i) == "\\"){
       $i++;
       next;
     }
     if($this->getChar($pgArray, $i) == "\""){
       $depth--;
       next;
     }
   }
   $arrayEnd = $i;
   $r[] = substr($pgArray, 1, $arrayEnd - 2);
   $r = array_merge($r,
     $this->toArray(substr($pgArray, $arrayEnd + 1)));
   return $r;
  }

  else{
   //an unquoted item
   $depth = 1;
   for($i=1; $depth && $i<strlen($pgArray); $i++){
     if($this->getChar($pgArray, $i) == "\\"){
       $i++;
       next;
     }
     if($this->getChar($pgArray, $i) == ","){
       $depth--;
       next;
     }
   }
   $arrayEnd = $i;
   if($arrayEnd == strlen($pgArray)){
     $r[] = $pgArray;
   }
   else{
     $r[] = substr($pgArray, 0, $arrayEnd-1);
   }
   $r = array_merge($r,$this->toArray(substr($pgArray,
     $arrayEnd)));
   return $r;
  }
}
function getChar($string, $pos=0){
  return substr($string, $pos, 1);
}
fmonteiro11 at hotmail dot com
15-Jan-2004 04:50
Another good source of knowledge is http://www.faqs.org/docs/ppbook/book1.htm
daniel at bichara dot com dot br
30-Dec-2002 11:04
Running RedHat Linux and Apache with suexec enabled you must include pgsql.so on each .php file using dl("pgsql.so") and remove "extension=pgsql.so" from php.ini, otherwise Apache (httpd) will not start.
anonymous at unknown dot com
29-Nov-2002 03:50
I just wanted to add to my previous post I've got the system up and running.
Environment: Windows XP, Apache 1.3.23, Php 4.3 RC2, PostGreSQL beta4 native windows build

Installation was fairly easy:
1. read the readme.txt
2. edit the setenv.bat as described in readme
3. run 'initdb'
   all execs are in /bin
   help is accessed like <command> --help
4. Start the psql deamon - you may want to create a batch file like
   'D:\postgres_beta4\bin\postmaster -h localhost -D D:/postgres_beta4/data'

   --deamon should be up and running now--

You can login into a shell from a console like
   'psql -h localhost -d <username>'

You must load the postgresql extension by editing the php.ini and restarting apache in order to access psql with php.

And one final not: when running
   $dbconn = pg_connect ("host=localhost port=5432 dbname=$dbname user=$user");
remember that $user and or $dbname is CASESENSITIVE.

Oh yeah, I created the data dir manually - don't know whether that was necessary

Grtz Vargo
anonymous at unknown dot com
29-Nov-2002 12:01
Here: http://archives.postgresql.org/pgsql-hackers/2002-11/msg00375.php
you can find the announcement for a native windows PostGreSQL port that is to be released in december (no cygwin). It also tells you where to download the beta (ftp://209.61.187.152/postgres/).
amk at eight13 dot com
27-Nov-2002 05:36
The list of postgresql function name changes is missing pg_errormessage being changed to pg_last_error.
swm at php dot net
22-Aug-2002 02:49
My talk on PHP and PostgreSQL which I presented at O'Reilly OSCON 2002 is now online.

http://www.alcove.com.au/oreilly/
mystran at wasteland dot pp dot htv dot fi
04-Feb-2002 01:46
Nice to know fact that I didn't find documented here.

PHP will return values of PostgreSQL boolean datatype as single character strings "t" and "f", not PHP true and false.

[Editor's Note]
't' or 'f' is valid boolean expression for PostgreSQL.

All values from PostgreSQL are strings, since PostgreSQL integer, float may be much larger than PHP's native int, double can handle. PostgreSQL array is not supported.
saberit at home dot com
15-Sep-2001 08:11
I tried compiling PHP from source with PostgreSQL support (./configure --with-pgsql=/usr/local/pgsql) and ran into a bunch of problems when trying to 'make'. The problem was that some of the PostgreSQL headers were not installed by default when I installed PostgreSQL from source. When installing PostgreSQL make sure you 'make install-all-headers' after you 'make install'.
hubert at hubertmuller dot com
09-Jul-2001 10:36
The best way to find the separated list of tables, sequences, keys etc is:

SELECT relname FROM pg_class WHERE relkind='<value>' AND relname !~ '^pg_';

<value> takes:
i for keys,
r for relations,
S for sequences

Note that all tables names that begins with 'pg_' are PostgreSQL internal tables (this explain why I use AND relname !~ '^pg_' condition).
passion at monkey dot org
28-Jun-2001 12:53
I've tried to mimic the following mysql database connection functions for postgres.
http://www.php.net/manual/en/function.mysql-list-dbs.php
http://www.php.net/manual/en/function.mysql-list-tables.php

These are assuming that you're passing in $link as the result from pg_connect:

function pg_list_dbs($link)

   $sql = 'SELECT datname FROM pg_database';
   return (pg_query($link, $sql));


function pg_list_tables($link)

   $sql = "SELECT relname FROM pg_class WHERE relname !~ '^pg_'";
   return (pg_query($link, $sql));
}
!spamcraig at ahdore dot com
15-Apr-2001 07:11
If you want to extract data from select statements, you need to store the result index, and then apply pg_result to that value. Basically, do this

$resultIdx = pg_query ($database, "select * from tablename");
$mySelect = pg_fetch_result($resultIdx, 0, 0);  // gets column 0 of tuple 0
echo("My select: [".$mySelect."]");

I'm new to php and had to do some fiddling around to work this out. It's reasonably elementary, but not demonstrated by the examples on these pages. Hopefully it will come in useful to someone else.
jdb30 at cornell.edu
06-Dec-2000 06:08
For further reading on PostgreSQL, see:
http://www.postgresql.org/docs/awbook.html
bleach at chek dot com
02-Mar-2000 06:36
If you want to see all the objects in a database, you can find that information in the pg_class table. <BR>
SELECT * FROM pg_class;<BR>
Now this is going to be kind of long and complex, to see how psql command handles the \d and other things. use the syntax.  psql -E <Database>, ie psql -E mydatabase <BR>
What this will do is show the SQL command used for everything. So when you type a \d or something, it shows the SQL query used for the result.

<posix_unamepg_affected_rows>
 Last updated: Sun, 02 May 2004
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2004 The PHP Group
All rights reserved.
This mirror generously provided by: Italia OnLine S.p.a.
Last updated: Fri May 21 04:11:23 2004 CEST