This topic describes how to connect a PHP client to a PolarDB cluster compatible with Oracle.

Prerequisites

Prepare the environment in Windows

  1. Download and install WampServer. For more information, see WampServer official website.
  2. Launch the PostgreSQL plug-in.
    1. Modify the php.ini file.
    2. Remove semicolons ; from the following code.

      Before you remove semicolons:

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

      After you remove semicolons:

      extension=php_pgsql.dll
      extension=php_pdo_pgsql.dll
  3. Copy the libpq.dll file from the C:\wamp\bin\php\php5.6.40 directory to the C:\windows\system32\ directory. Note: php5.6.40 is used in this example, and the actual directory is subject to your client version.
  4. Restart the Apache service.

Prepare the environment in Linux

  1. Install the php-pgsql.x86_64 driver.
    sudo yum install php-pgsql.x86_64
  2. Modify the php.ini file.
    vim /etc/php.ini
  3. Add the following content to the php.ini file.
    extension=php_pgsql.so

Connect to Apsara PolarDB

After you prepare the environment in Windows or Linux, you can run a PHP script to connect to the Apsara PolarDB database.

The following sample code shows how to use PHP to connect to the Apsara PolarDB cluster.

<? php
 $host    = "host=xxxx";
 $port    = "port=xxxx";
 $dbname   = "dbname=xxxx";
 $credentials = "user=xxxx password=xxxxx";
 $db = pg_connect( "$host $port $dbname $credentials" );
 if(! $db){
  echo "Error : Unable to open database\n";
 } else {
  echo "Opened database successfully\n";
 }
 $sql =<<<EOF
  select * from pg_roles;
EOF;
 $ret = pg_query($db, $sql);
 if(! $ret){
  echo pg_last_error($db);
 } else {
  echo "Records created successfully\n";
 }
 $results = pg_fetch_all($ret);
 print_r($results);
 pg_close($db);
? >

In the preceding sample code, the connection information of Apsara PolarDB consists of parameters, such as host, port, dbname, and credentials, as shown in the following table.

Parameter Example Description
host "host=xxxxxx" The endpoint of the Apsara PolarDB cluster. For more information about how to retrieve the endpoint, see View or apply for an endpoint.
port "port=1521" The port of the Apsara PolarDB cluster. Default value: 1521.
dbname "dbname=xxxx" The name of the database to be connected.
credentials "user=xxx password=xxxx" The username and password used to log on to the Apsara PolarDB cluster.

For more information about PHP APIs, see PHP documentation.