How can I switch to a different database in POSTGRES via PHP?
I mean a way similar to
mysqli_select_db( $db_conn, $db_name )
on any other workaround, but using the same connection.
The concept is different:
Each MySQL server has ONE SINGLE database, and inside this SINGLE database, it might have many database schemas called "database".
Each PostgreSQL can have many databases, and each database might have many schemas.
When you connect to a database (the real database, not a schema), you can change the schema (or "database" in MySQL) that is used. And you can see what schema you're currently using.
SELECT current_database()
, current_schema();
https://www.postgresql.org/docs/current/sql-createschema.html https://dev.mysql.com/doc/refman/9.4/en/create-database.html
From the MySQL documentation:
CREATE SCHEMA is a synonym for CREATE DATABASE.
There is no direct equivalent (obviously you can disconnect and reconnect to a different DB, but not switch within the same connection).
I don't know if mysql has schemas (namespaces) in-database yet, but if not traditionally schemas were considered the closest equivalent. You can control permissions at a schema level, and have cross-schema joins etc within a single PostgreSQL database.
pg_close and again pg_connect ?If you are using psql, then it's
\c yourdb
In PHP you can use pg_connect to connect to a PostgresSQL database. You can pass the connection string and it will return a connection object. If you already had a connection to another database and you no longer need it, then it is recommended to use pg_close to close that connection.
EDIT
You can implement a wrapper for this purpose which will encapsulate the close and the connect and whose name would look alike somewhat the name you had for mysqli:
pg_select_db(string $connection_string, ?PgSql\Connection $connection = null, int $flags = 0): PgSql\Connection|false {
pg_close($connection);
return pg_connect($connection_string, $flags);
}
and then you have a single method to call.
databaseis a synonym forschema, whereas in Postgres it is actually a differentdatabase. You will need to either: 1) Disconnect and reconnect to new database or 2) Or use postgres-fdw to link(it creates a behind the scenes connection) the databases.