Submitted by Kiran on Sun, 02/15/2009 - 16:06
PostgreSQL is a common open source relational database system often used by PHP programmers.
Here we will discuss a PHP script to connect, insert data, retrieve data, and close the connection.
Let's create an example table in PostgreSQL and insert some dummy data:
create table example(
id serial,
desc varchar(255) not null,
qty int not null,
primary key(id)
);
insert into example (desc, qty) values ('test1', 10);
insert into example (desc, qty) values ('test2', 1);
insert into example (desc, qty) values ('test3', 2);
Now we will use php to access the PostgreSQL Database:
<?php
// Open the database connection
if (!($db = pg_connect(
'host=localhost dbname=dbname user=username password=yourpassword'))) {
// Handle errors
die('SQL ERROR: Connection failed: ' . pg_last_error($db));
}
// Prepare a SQL insert: assume we received the description from the user
$desc = 'TEST';
$escaped = pg_escape_string($desc);
$sql = "insert into example (desc, qty) values ('{$escaped}', 0)";
// Do the insertion:
if (!(pg_query($db, $sql))) {
// Give an error statement:
die('SQL INSERT ERROR: ' . pg_last_error($db). " - Query was: {$sql}");
}
// Select data from the table:
$sql = 'select id, desc from example order by id asc';
if (!($result = pg_query($db, $sql))) {
// Give an error statement:
die('SQL SELECT ERROR: ' . pg_last_error($db). " - Query was: {$sql}");
}
// Read all the data back in as associative arrays
while ($row = pg_fetch_assoc($result)) {
echo "{$row['id']}. {$row['desc']}
\n";
}
// Now close the connection
pg_close($db);
?>
»
- Kiran's blog
- 637 reads













Post new comment