Hinweis:
Nicht alle Funktionen sind in allen Versionen verfügbar. Es hängt davon ab, welche libpq-Version (die PostgreSQL-C-Client-Bibliothek) auf Ihrem Rechner verfügbar ist und wie libpq kompiliert wurde. Falls eine Funktion nicht verfügbar ist, liegt es daran, dass libpq die nötigen Routinen nicht unterstützt, die diese Funktion braucht.
Hinweis:
Die meisten PostgreSQL-Funktionen nehmen den Parameter connection als ersten optionalen Parameter entgegen. Falls er nicht angegeben wurde, wird die zuletzt geöffnete Verbindung benutzt. Wenn keine geöffnete Verbindung existiert, geben die Funktionen FALSE zurück.
Hinweis:
PostgreSQL wandelt automatisch alle Bezeichner (beispielsweise Tabellen- oder Spaltennamen) in Kleinbuchstaben um, und zwar sowohl bei der Erzeugung der Objekte als auch in Abfragen. Um Namen in Groß- und Kleinschreibung oder in Großbuchstaben zu erzwingen, müssen diese in doppelte Anführungszeichen ("") eingeschlossen werden.
Hinweis:
PostgreSQL stellt keine speziellen Kommandos zur Verfügung, um Informationen über ein Datenbank-Schema (z.B. alle Tabellen in der aktuellen Datenbank) zu erhalten. Stattdessen gibt es ab der Version 7.4 und höher ein Standard-Schema, das information_schema, in dem alle notwendigen Informationen in System-Views enthalten und die einfach abzufragen sind. Ausführliche Informationen darüber gibt es in der » PostgreSQL-Dokumentation.
Parsing a postgres array can be a tricky problem, he's my take on this, it handles multi-dimensional arrays plus escaping using a nasty regexp to determine the limits of each data-item.
<?php
function pg_array_parse( $text, &$output, $limit = false, $offset = 1 )
{
if( false === $limit )
{
$limit = strlen( $text )-1;
$output = array();
}
if( '{}' != $text )
do
{
if( '{' != $text{$offset} )
{
preg_match( "/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/", $text, $match, 0, $offset );
$offset += strlen( $match[0] );
$output[] = ( '"' != $match[1]{0} ? $match[1] : stripcslashes( substr( $match[1], 1, -1 ) ) );
if( '},' == $match[3] ) return $offset;
}
else $offset = pg_array_parse( $text, $output[], $limit, $offset+1 );
}
while( $limit > $offset );
return $output;
}
?>
<?php
function pg_export_table_content() {
/*
* this function exports all contents of all tables in the file import.sql
* $pg-> = my postgres db class
*/
$tables = array();
$mytables = array();
$all_tables = $pg->query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' and table_type = 'BASE TABLE';");
while($row = $pg->fetch_row($all_tables)) {
$tables[] = $row->table_name;
}
$esc[] = "value";
$esc[] = "time";
$esc[] = "order";
$esc[] = "comment";
$esc[] = "group";
$esc[] = "time";
$esc[] = "name";
$esc[] = "alter";
$esc[] = "user";
foreach($tables as $v1) {
$myqry = "select * from \"".$v1."\"";
$myres = $pg->query($myqry);
while($myrow = $pg->fetch_assoc($myres)) {
$mytables[$v1][] = $myrow;
}
}
$handle = fopen("./import.sql", "w+");
foreach($mytables as $k1 => $v1) {
foreach($v1 as $k2 => $v2) {
foreach($v2 as $k3 => $v3) {
if(in_array($k3, $esc)) {
$mycols[] = "\"".$k3."\"";
}
else {
$mycols[] = $k3;
}
$col_qry = "select column_name, data_type from information_schema.columns where table_name = '".$k1."'";
$col_res = $pg->query($col_qry);
while($col_row = $pg->fetch_assoc($col_res)) {
$mydatatypes[$col_row["column_name"]] = $col_row["data_type"];
}
if(($mydatatypes[$k3] == "integer") || ($mydatatypes[$k3] == "bigint") || ($mydatatypes[$k3] == "smallint")) {
if(empty($v3)) {
$myval[] = "NULL";
}
else {
$myval[] = $v3;
}
}
else {
$myval[] = "'".$v3."'";
}
}
$myquery = "insert into ".$k1."(".implode(",", $mycols).") VALUES (".implode(",", $myval).");";
unset($myval,$mycols);
fwrite($handle, $myquery."\n");
}
}
fclose($handle);
}
?>
There is no need to parse a postgres array. The stored procedures should never return an array. Use SETOF instead.
Parse a PostgreSQL array of any dimension to a PHP array.
Works great if you absolutely trust the data ;-)
<?php
function pg_array_parse($array, $asText = true) {
$s = $array;
if ($asText) {
$s = str_replace("{", "array('", $s);
$s = str_replace("}", "')", $s);
$s = str_replace(",", "','", $s);
} else {
$s = str_replace("{", "array(", $s);
$s = str_replace("}", ")", $s);
}
$s = "\$retval = $s;";
eval($s);
return $retval;
}
?>
Quick and dirty emulation of the mysql_select_db () function for Postgres:
<?php
function pg_select_db ($dbName)
{
$query = '\connect '.pg_escape_string ($dbName);
if ($result = pg_query ($query))
return (true);
else
return (false);
}
?>
Obviously not a great example, but it at least demonstrates how to implement mysql_select_db functionality when using Postgres. Or you could always use schemas :)
Chris KL: Will parse well {"\\"}? The second " will be treat as escaped while it shoudn't...
Lots of advice on stored procedures didn't work for me. This did:
<?php
$response = pg_query( $connection, "BEGIN; DECLARE s CURSOR FOR SELECT get_consumer('harry'); FETCH ALL IN s; END;" );
?>
..where harry looks like this:
CREATE OR REPLACE FUNCTION get_consumer( varchar )
RETURNS refcursor
AS '
DECLARE
_name ALIAS FOR $1;
r refcursor;
BEGIN
OPEN r FOR SELECT name FROM consumer
WHERE
consumer.name = _name
;
RETURN r;
END
' LANGUAGE 'plpgsql';
Here is a better array parser for PHP. It will work with 1-d arrays only. Unlike the example below it will work in all cases.
/**
* Change a db array into a PHP array
* @param $arr String representing the DB array
* @return A PHP array
*/
function phpArray($dbarr) {
// Take off the first and last characters (the braces)
$arr = substr($dbarr, 1, strlen($dbarr) - 2);
// Pick out array entries by carefully parsing. This is necessary in order
// to cope with double quotes and commas, etc.
$elements = array();
$i = $j = 0;
$in_quotes = false;
while ($i < strlen($arr)) {
// If current char is a double quote and it's not escaped, then
// enter quoted bit
$char = substr($arr, $i, 1);
if ($char == '"' && ($i == 0 || substr($arr, $i - 1, 1) != '\\'))
$in_quotes = !$in_quotes;
elseif ($char == ',' && !$in_quotes) {
// Add text so far to the array
$elements[] = substr($arr, $j, $i - $j);
$j = $i + 1;
}
$i++;
}
// Add final text to the array
$elements[] = substr($arr, $j);
// Do one further loop over the elements array to remote double quoting
// and escaping of double quotes and backslashes
for ($i = 0; $i < sizeof($elements); $i++) {
$v = $elements[$i];
if (strpos($v, '"') === 0) {
$v = substr($v, 1, strlen($v) - 2);
$v = str_replace('\\"', '"', $v);
$v = str_replace('\\\\', '\\', $v);
$elements[$i] = $v;
}
}
return $elements;
}
Here is some quick and dirty code to convert Postgres-returned arrays into PHP arrays. There's probably a billion bugs, but since I'm only dealing with variable-depth-and-length arrays of integers, it works for my needs.
Most notably, any data that might have commas in it won't work right...
<?php
function PGArrayToPHPArray($pgArray)
{
$ret = array();
$stack = array(&$ret);
$pgArray = substr($pgArray, 1, -1);
$pgElements = explode(",", $pgArray);
ArrayDump($pgElements);
foreach($pgElements as $elem)
{
if(substr($elem,-1) == "}")
{
$elem = substr($elem,0,-1);
$newSub = array();
while(substr($elem,0,1) != "{")
{
$newSub[] = $elem;
$elem = array_pop($ret);
}
$newSub[] = substr($elem,1);
$ret[] = array_reverse($newSub);
}
else
$ret[] = $elem;
}
return $ret;
}
?>
Setting up PostgreSQL for higher security PHP connection.
Case:
We want to connect to PostgreSQL database using username and password supplied by webuser at login time.
Fact (Linux):
Apache (perhaps other servers, too) running the server as (default to) apache user account. So if you connect to PostgreSQL using default user, apache will be assingned for it. If you hard code the user and password in your PHP script, you'll loose security restriction from PostgreSQL.
Solution:
(You are assumed to have enough privilege to do these things, though)
1. Edit pg_hba.conf to have the line like the one below
host db_Name [web_server_ip_address] [ip_address_mask] md5
2. Add to you script the login page that submits username and password.
3. Use those information to login to PostgreSQL like these...
<?
$conn = "host=$DBHost port=$DBPort dbname=$DBName ".
"user='{$_POST['dbUsername']}' password='{$_POST['dbPassword']}'";
$db = pg_connect ($conn);
[your other codes go here...]
?>
4. You must add users in PostgreSQL properly.
5. For your convenience, you can store the username and password to $_SESSION variable.
Good luck.
Anis WN
There is an example:
<?php
/*
* Define PostgreSQL database server connect parameters.
*/
define('PGHOST','10.0.0.218');
define('PGPORT',5432);
define('PGDATABASE','example');
define('PGUSER', 'root');
define('PGPASSWORD', 'nopass');
define('PGCLIENTENCODING','UNICODE');
define('ERROR_ON_CONNECT_FAILED','Sorry, can not connect the database server now!');
/*
* Merge connect string and connect db server with default parameters.
*/
pg_pconnect('host=' . PGHOST . ' port=' . PGPORT . ' dbname=' . PGDATABASE . ' user=' . PGUSER . ' password=' . PGPASSWORD);
/*
* generate sql statements to call db-server-side stored procedure(or function)
* @parameter string $proc stored procedure name.
* @parameter array $paras parameters, 2 dimensions array.
* @return string $sql = 'select "proc"(para1,para2,para3);'
* @example pg_prepare('userExists',
* array(
* array('userName','chin','string'),
* array('userId','7777','numeric')
* )
* )
*/
function pg_prepare($proc, $paras)
{
$sql = 'select "' . $proc . '"(';
$sql .= $paras[0][2] == 'numeric' ? $paras[0][1] : "'" . str_replace("'","''",$paras[0][1]) . "'";
$len = count($paras);
for ($i = 1; $i < $len; $i ++)
{
$sql .= ',';
$sql .= $paras[$i][2] == 'numeric' ? $paras[$i][1] : "'" . str_replace("'","''",$paras[$i][1]) . "'";
}
$sql .= ');';
return $sql;
}
?>
Yes, PHP does support stored procedures
You have to add "select" before the name of the
procedure, just like that:
$result = pg_querry($conn, "SELECT procedure_x($aa)");
if a procedure returns a cursor you do something like that:
$result = pg_query($conn, "SELECT procedure_x('rcursor'); FETCH ALL IN rcursor");
for just a list of tables, this works with postgresql-7.2.1:
function pg_list_tables($db) {
$sql = "select relname from pg_stat_user_tables order by relname;";
return pg_query($db, $sql);
}
I've found another function to mimic the following mysql list tables function (http://www.php.net/manual/en/function.mysql-list-tables.php) that's more useful for my target:
function pg_list_tables() {
$sql = "SELECT a.relname AS Name
FROM pg_class a, pg_user b
WHERE ( relkind = 'r') and relname !~ '^pg_' AND relname !~ '^sql_'
AND relname !~ '^xin[vx][0-9]+' AND b.usesysid = a.relowner
AND NOT (EXISTS (SELECT viewname FROM pg_views WHERE viewname=a.relname));";
return(pg_query($conn, $sql));
}
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.
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
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.
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'.
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).
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));
}
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.
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.