All Products
Search
Document Center

PolarDB:PHP

Last Updated:Mar 28, 2026

Connect a PHP application to a PolarDB for Oracle cluster using the pgsql extension.

Prerequisites

Before you begin, ensure that you have:

Set up the environment

Windows

  1. Download and install WampServer.

  2. Enable the PostgreSQL extension in php.ini. Open php.ini and uncomment the following lines by removing the leading semicolons: Before:

    ;extension=php_pgsql.dll
    ;extension=php_pdo_pgsql.dll

    After:

    extension=php_pgsql.dll
    extension=php_pdo_pgsql.dll
  3. Copy libpq.dll from C:\wamp\bin\php\php5.6.40 to C:\windows\system32\.

    The path php5.6.40 is an example. Use the directory that matches your installed PHP version.
  4. Restart the Apache service.

Linux

  1. Install the PHP PostgreSQL driver:

    sudo yum install php-pgsql.x86_64
  2. Open php.ini:

    vim /etc/php.ini
  3. Add the following line:

    extension=php_pgsql.so

Connect to PolarDB

Replace the placeholders in the following script with your actual values before running it.

PlaceholderDescriptionExample
<cluster-endpoint>The endpoint of your PolarDB cluster. See View or apply for an endpoint.pc-xxxx.polardb.aliyuncs.com
<port>The port of your PolarDB cluster. Default: 1521.1521
<database-name>The name of the database to connect to.mydb
<username>The database account username.myuser
<password>The database account password.

The script uses pg_connect() to establish the connection, pg_query() to run a SQL query, pg_fetch_all() to retrieve the results, and pg_close() to close the connection. If any step fails, pg_last_error() returns the error details.

<?php
$host        = "host=<cluster-endpoint>";
$port        = "port=<port>";
$dbname      = "dbname=<database-name>";
$credentials = "user=<username> password=<password>";

$db = pg_connect("$host $port $dbname $credentials");
if (!$db) {
    echo "Error: Unable to open database\n";
    echo pg_last_error();
    exit;
}

echo "Connected successfully\n";

$sql = "SELECT * FROM pg_roles;";
$ret = pg_query($db, $sql);
if (!$ret) {
    echo pg_last_error($db);
} else {
    echo "Query executed successfully\n";
    $results = pg_fetch_all($ret);
    print_r($results);
}

pg_close($db);
?>

What's next

For the full list of PHP PostgreSQL functions, see the PHP pgsql extension documentation.