Communicate with PostgreSQL using PHP

0
Your rating: None

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); ?>

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.

Cumulus Tag Cloud

Kiran Says

I love work environment which is:

Informal yet professional
Demanding yet rewarding
Challenging yet inspiring
Mediocrity is not an option
Having fun is serious business
Making mistakes is human
Forgiveness is Company Policy

Travelling Sucks