begin.py
begin.py

Reputation: 161

Access a specific schema in a PostgreSQL database via PHP

I have a PostgreSQL database userdb with 5 schemas.

Schema 1- Persons
Schema 2- Project
Schema 3- Shop
Schema 4- Test

I was able to connect to the database using pg_connect. How do I access a specific schema in that database?

I was able to connect to a schema when there was only one in the database. But now since I have multiple schemas I am having difficulty in accessing any specific one.

 <?php
 // attempt a connection
 $dbh = pg_connect("host=**.****.*******.*** dbname=test user=merlin port=5433 password=passw123");
 if (!$dbh) {
     die("Error in connection test: " . pg_last_error());
 } 
// execute query
 $sql = "SELECT * FROM test.country";
 $result = pg_query($dbh, $sql);
 if (!$result) {
     die("Error in SQL query: " . pg_last_error());
 }       

 // iterate over result set
 // print each row
 while ($row = pg_fetch_array($result)) {
     echo "Country code: " . $row[0] . "<br />";
     echo "Country name: " . $row[1] . "<p />";
 }       

 // free memory
 pg_free_result($result);       

 // close connection
 pg_close($dbh);      
?>

Upvotes: 1

Views: 12562

Answers (3)

Erwin Brandstetter
Erwin Brandstetter

Reputation: 656241

Schema-qualify the table name as Clodoaldo already advised. Or set the search_path for a permanent effect. It works much like a search path in the file system.

How permanent depends on how you set it. See:

Upvotes: 3

sdfor
sdfor

Reputation: 6438

use:
SET search_path TO myschema; or

SET search_path TO myschema, myschemab;

https://www.postgresql.org/docs/9.4/static/ddl-schemas.html

Upvotes: 3

Clodoaldo Neto
Clodoaldo Neto

Reputation: 125204

Qualify the table with the schema name

select *
from my_schema.aircraft

Upvotes: 6

Related Questions