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);      
?>
3
  • What is the difficulty you are having? Commented Apr 19, 2013 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. Commented Apr 19, 2013 at 16:45
  • Is the name of the table aircraft or "Aircraft"? More about mixed case identifiers here: stackoverflow.com/questions/8792912/… Commented Apr 20, 2013 at 17:10

3 Answers 3

6

Qualify the table with the schema name

select *
from my_schema.aircraft
Sign up to request clarification or add additional context in comments.

1 Comment

I am getting this error - Error in SQL query: ERROR: schema "aircraft" does not exist at character 15
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

Comments

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:

1 Comment

@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.