All Products
Search
Document Center

PolarDB:PHP

Last Updated:Mar 28, 2026

Connect a PHP client to a PolarDB cluster compatible with Oracle using the pg_connect() function from the pgsql extension.

Prerequisites

Set up the PHP environment

Choose the setup steps for your operating system.

Windows

  1. Download and install WampServer.

  2. Enable the PostgreSQL plug-in by modifying php.ini: Before:

    1. Open php.ini. The file is typically located at C:\wamp\bin\php\php<version>\php.ini, where <version> matches your installed PHP version (for example, php5.6.40).

    2. Find the following lines and remove the leading semicolons to uncomment them:

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

    After:

    extension=php_pgsql.dll
    extension=php_pdo_pgsql.dll

    If the lines do not exist in the file, add them without the semicolons.

  3. Copy libpq.dll from C:\wamp\bin\php\php<version> to C:\windows\system32\.

  4. Restart the Apache service.

Linux

  1. Install the php-pgsql driver:

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

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

    extension=php_pgsql.so

Connect to PolarDB

The following script connects to PolarDB, runs a query against pg_roles, and prints the results.

<?php
// Connection parameters — replace with your actual values
$host        = "<cluster-endpoint>";
$port        = "1521";
$dbname      = "<database-name>";
$user        = "<username>";
$password    = "<password>";

// Establish a connection
$db = pg_connect("host=$host port=$port dbname=$dbname user=$user password=$password");

if (!$db) {
    echo "Error: Unable to connect to the database.\n";
    exit(1);
} else {
    echo "Connected successfully.\n";
}

// Run a query
$sql = "SELECT * FROM pg_roles;";
$result = pg_query($db, $sql);

if (!$result) {
    echo pg_last_error($db);
} else {
    echo "Query executed successfully.\n";
    $rows = pg_fetch_all($result);
    print_r($rows);
}

// Close the connection
pg_close($db);
?>

Replace the placeholders with your actual values:

PlaceholderDescriptionExample
<cluster-endpoint>Endpoint of the PolarDB cluster. See View or apply for an endpoint."host=xxxxxx"
<database-name>Name of the database to connect to"dbname=xxxx"
<username>Username for the database account"user=xxx"
<password>Password for the database account

The default port for PolarDB clusters compatible with Oracle is 1521.

What's next

For a full list of PHP functions for PostgreSQL connections, see the PHP pgsql documentation.