ทำตามคำแนะนำด้านล่างเพื่อเรียนรู้วิธีเชื่อมต่อแอปพลิเคชัน PHP ไปยังโฮสต์ภายใน Ruk-Com Cloud กับเซิร์ฟเวอร์ฐานข้อมูล PostgreSQL
สร้าง Environment
1. ล็อกอินไปยังแดชบอร์ด Ruk-Com Cloud สร้าง Environment โดยเลือกที่แท็บ PHP เว็บเซิร์ฟเวอร์เป็ฯ Apache และ ระบบฐานข้อมูล PostgreSQL

3. ข้อมูลการเข้าใช้งานจะถูกส่งไปยังอีเมลของคุณ

ตอนนี้คุณสามารถเข้าถึงฐานข้อมูลของคุณผ่านแอดมินพาเนล และเชื่อมต่อกับแอปพลิเคชัน PHP
กำหนดค่าการเชื่อมต่อฐานข้อมูล
1. คลิกปุ่ม Config ของเซิร์ฟเวอร์ Apache

2. ไปที่โฟลเดอร์ etc และเปิดไฟล์ php.ini
เพิ่ม extension=pgsql.so ในบรรทัดตามที่แสดงในภาพด้านล่าง

3. บันทึกการเปลี่ยนแปลง และรีสตาร์ทโหนดของ Apache

4. มีฟังก์ชัน PG หลักสองฟังก์ชัน PG functions สำหรับปฏิบัติการกับเซิร์ฟเวอร์ฐานข้อมูล
- ตัวอย่างโค้ดสำหรับเชื่อมต่อ PostgreSQL:
pg_connect(“host={host} port={port} dbname={dbname} user={user} password={password}");
- {host} – the PostgreSQL server Host (i.e. access URL without http://) that you’ve received via email, for example node171206-php-postgresql.jelastic.com
- {port} – a connection port (the default one is 5432)
- {dbname} – a name of your database
- {user} – an account name to access database with (we’ll use the default webadmin one)
- {password} – a password for the appropriate user
- closing PostgreSQL connection: pg_close()
5. คุณต้องเขียนฟังก์ชันที่จำเป็นในทุกหน้า * .php ที่เชื่อมต่อกับฐานข้อมูล
ตรวจสอบการเชื่อมต่อ
– ตรวจสอบการเชื่อมต่อโดยใช้โค้ดนี้:
<?php
$dbconn = pg_connect("host=php-postgressql.app.ruk-com.cloud port=5432 dbname=postgres user=webadmin password=passw0rd");
//connect to a database named "postgres" on the host "host" with a username and password
if (!$dbconn){
echo "<center><h1>Doesn't work =(</h1></center>";
}else
echo "<center><h1>Good connection</h1></center>";
pg_close($dbconn);
?>
– วางโค้ดที่ใช้ทดสอบไว้ที่ Path /var/www/webroots/ROOT/connect.php

– โค้ดตัวอย่างสำหรับการส่งออกเป็นตาราง:
<?php
$conn = pg_connect("host=postgres.jelastic.com port=5432 dbname=postgres user=webadmin password=passw0rd");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
$result = pg_query($conn, "SELECT * FROM test_table");
if (!$result) {
echo "An error occurred.\n";
exit;
}
while ($row = pg_fetch_row($result)) {
echo "value1: $row[0] value2: $row[1]";
echo "<br />\n";
}
?>
คุณสามารถใช้ตัวอย่างที่อธิบายไว้ข้างต้นเพื่อสร้างแอปพลิเคชัน PHP ของคุณเองซึ่งใช้การเชื่อมต่อกับฐานข้อมูล PostgreSQL