Connect a PHP client to a PolarDB cluster compatible with Oracle using the pg_connect() function from the pgsql extension.
Prerequisites
A database account is created in the PolarDB cluster. For more information, see Create a database account.
The IP address of the host that you use to access the PolarDB cluster is added to a whitelist. For more information, see Configure a cluster whitelist.
Set up the PHP environment
Choose the setup steps for your operating system.
Windows
Download and install WampServer.
Enable the PostgreSQL plug-in by modifying
php.ini: Before:Open
php.ini. The file is typically located atC:\wamp\bin\php\php<version>\php.ini, where<version>matches your installed PHP version (for example,php5.6.40).Find the following lines and remove the leading semicolons to uncomment them:
;extension=php_pgsql.dll ;extension=php_pdo_pgsql.dllAfter:
extension=php_pgsql.dll extension=php_pdo_pgsql.dllIf the lines do not exist in the file, add them without the semicolons.
Copy
libpq.dllfromC:\wamp\bin\php\php<version>toC:\windows\system32\.Restart the Apache service.
Linux
Install the
php-pgsqldriver:sudo yum install php-pgsql.x86_64Open
php.ini:vim /etc/php.iniAdd 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:
| Placeholder | Description | Example |
|---|---|---|
<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.