Connect a PHP application to a PolarDB for Oracle cluster using the pgsql extension.
Prerequisites
Before you begin, ensure that you have:
A database account on your PolarDB cluster. See Create a database account.
The IP address of your application host added to the cluster whitelist. See Configure a whitelist for a cluster.
Set up the environment
Windows
Download and install WampServer.
Enable the PostgreSQL extension in
php.ini. Openphp.iniand uncomment the following lines by removing the leading semicolons: Before:;extension=php_pgsql.dll ;extension=php_pdo_pgsql.dllAfter:
extension=php_pgsql.dll extension=php_pdo_pgsql.dllCopy
libpq.dllfromC:\wamp\bin\php\php5.6.40toC:\windows\system32\.The path
php5.6.40is an example. Use the directory that matches your installed PHP version.Restart the Apache service.
Linux
Install the PHP PostgreSQL driver:
sudo yum install php-pgsql.x86_64Open
php.ini:vim /etc/php.iniAdd the following line:
extension=php_pgsql.so
Connect to PolarDB
Replace the placeholders in the following script with your actual values before running it.
| Placeholder | Description | Example |
|---|---|---|
<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.