<?php

//define variables used with the database
//usually this goes in an include file
$PG_HOST="localhost";
$PG_PORT=5432;
$PG_DATABASE="pguser";
$PG_USER="pguser";

$PG_PASS="";

//let's open the database
$dbconn=pg_connect( "dbname=$PG_DATABASE host=$PG_HOST port=$PG_PORT user=$PG_USER password=$PG_PASS" );
if ( ! $dbconn ) {
    echo "Error connecting to the database !<br> " ;
    printf("%s", pg_errormessage( $dbconn ) );
    exit();
}

//the database handle is $dbconn
//run a sql command to insert another record
$sqlcom="insert into friends values ('Marius', 'marius@marius.com')";

$dbres = pg_exec($dbconn, $sqlcom );
if ( ! $dbres ) {
    echo "Error : " + pg_errormessage( $dbconn );
    exit();
}

//let me know I've been added to the database by sending me an email
mail("marius@marius.com", "Lucky winner !", 
"You've just won a row in our database. Congratulations !", "From : boss@db.com");
//yes, it's that simple
//( sending an email I mean, it's not so easy to win :)

//what do we have now in the database ?

$sqlcom="select * from friends";

$dbres = pg_exec($dbconn, $sqlcom );
if ( ! $dbres ) {
    echo "Error : " + pg_errormessage( $dbconn );
    exit();
}

//and interpret the results
$row=0;
$rowmax=pg_NumRows($dbres);

while ($row<$rowmax)
{
    $do = pg_Fetch_Object($dbres, $row);
    
    $s="<p>$do->name | $do->email\n";
    printf("%s", $s);
    
    $row++;
}

//close the database
pg_close( $dbconn );

//That's all. This isn't a tutorial to PHP, I wanted to show you how
//it can be done. As you can see, it isn't hard at all
?>
