1

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);      
?>
begin.py
  • 161
  • 1
  • 1
  • 9
  • What is the difficulty you are having? – Clodoaldo Neto Apr 19 '13 at 16:43
  • it gives me this error: `Error in SQL query: ERROR: relation "aircraft" does not exist at character 15.` Aircraft is a table in one of my schemas. – begin.py Apr 19 '13 at 16:45
  • Is the name of the table `aircraft` or `"Aircraft"`? More about mixed case identifiers here: http://stackoverflow.com/questions/8792912/postgresql-error-relation-already-exists/8793441#8793441 – Erwin Brandstetter Apr 20 '13 at 17:10

3 Answers3

6

Qualify the table with the schema name

select *
from my_schema.aircraft
Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260
  • I am getting this error - `Error in SQL query: ERROR: schema "aircraft" does not exist at character 15` – begin.py Apr 21 '13 at 00:10
3

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:

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
  • @Clodoaldo 's method doesnt seem to work for some reason. my php code. And ive only just begun SQL n PHP so I dint understand you procedure. I am editing my question to incorporate my code now. – begin.py Apr 19 '13 at 19:33
3

use:
SET search_path TO myschema; or

SET search_path TO myschema, myschemab;

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

sdfor
  • 6,324
  • 13
  • 51
  • 61