PHP
Relyt supports the PostgreSQL connection protocol, which means any tools or software that can connect to PostgreSQL can also be used for Relyt connections.
This guide will walk you through the process of connecting to Relyt using PHP.
The OS used in the following example is MacOS. If you use other types of OS, change the code accordingly.
1. Prepare the environment
Install PHP with PDO and the PDO PostgreSQL extension in your environment.
Skip this step if your environment is ready.
brew install php
brew install postgresql
2. Create a PHP program
-
Create a .php file:
vim relyt_demo.php
-
Write the program code in the file:
<?php
$host = "<endpoint_domain>";
$port = <endpoint_port>;
$user = "<dw_user>";
$password = "<dw_user_password>";
$dbname = "<database>";
try {
// Connect to your Relyt database
$conn = new PDO("pgsql:host=$host;port=$port;dbname=$dbname;user=$user;password=$password");
// Set the PDO error mode to EXCEPTION
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Drop table items if it exists and create a new table named items
$conn->exec("DROP TABLE IF EXISTS items;");
$conn->exec("CREATE TABLE IF NOT EXISTS items (id INTEGER, name VARCHAR);");
// Insert data into the table
$conn->exec("INSERT INTO items (id, name) VALUES (1, 'item1'), (2, 'item2');");
// Query data and obtain data as PHP objects
$stmt = $conn->prepare("SELECT * FROM items;");
$stmt->execute();
// Set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $k=>$v) {
print_r($v);
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>The following table describes the related variables. Set them to the actual values when in actual use.
Variable Description $host The public endpoint for connecting to the Relyt DW service unit. $port The port for connecting to the Relyt DW service unit. The default port is 5432. $user The name of the DW user that connects to the Relyt DW service unit. $password The password of the DW user. $dbname The name of the Relyt database to connect.
The SQL commands provided in the example perform the following operations in sequence:
-
Drop a table named
items
if it exists -
Create a table named
items
-
Insert data to table
items
-
Query data from
items
They are for reference only. You can replace them with any SQL commands you want to run.
-
3. Run the program
Run the program:
php relyt_demo.php