2

I have the following string connection:

$string_connection = "host=localhost port=5432 user=postgres password=postgres";
$conn = pg_connect($string_connection );

Later in my code, I need to select a database:

pg_connect("dbname=my_database");

But, always I have the following error:

Warning: pg_connect(): Unable to connect to PostgreSQL server: fe_sendauth: no password supplied in ..\class.databases.php on line 142

But, in the example of PHP.net, they do this. Another example:

pg_query($conn,'\connect my_database');

Why this dont work?

When I do a backup with PgAdmin, I got the following strings:

SET statement_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = off;
SET check_function_bodies = false;
SET client_min_messages = warning;
SET escape_string_warning = off;

DROP DATABASE my_database;

CREATE DATABASE my_database WITH ENCODING = 'UTF8' LC_COLLATE = 'Portuguese_Brazil.1252' LC_CTYPE = 'Portuguese_Brazil.1252';

ALTER DATABASE my_database OWNER TO postgres;

\connect my_database

Whe I try to run this script with pg_query, I have erros:

Warning: pg_query(): Query failed: ERRO: syntax error in "\" LINE 1: \connect my_database ^

I need to select a dabatase to create a schema then create my tables... I dont know how to do this with Postgres.

10
  • Why not select the database when you initially run pg_connect? Commented Jul 17, 2013 at 17:56
  • 1
    Because the user will select or create a database, where it can create a schema and then run a set of queries / sql script. Commented Jul 17, 2013 at 18:01
  • In that case, you're going to have to pass all the parameters in on the second pg_connect call, I think. I assume the examples on php.net are for databases that don't require passwords for a connection. Commented Jul 17, 2013 at 18:04
  • Yeah, I think too. But what about the pg_query($conn,'\connect my_database'); ? Commented Jul 17, 2013 at 18:05
  • Where did you see that code? I can't find it on the php.net pages for pg_connect or pg_query. Commented Jul 17, 2013 at 18:07

1 Answer 1

2

Add "dbname=my_database" to your connection string to select a database at conection time.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I know, but if need to change the database after? I need to close and re-connect?

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.