Search code examples
phppostgresqldatabase-permissions

Drop PostgreSql DB from php


Is there any way to write DROP DATABASE [ IF EXISTS ] name from php script? Seems that I need something similar to mysql_drop_db just for Postrge.

How my $connStr in $conn = pg_connect($connStr) must look like to have rights to do this command? What db I must be connected?


Solution

    1. You have to be connected to a different db on same cluster as superuser role or db owner

    https://www.postgresql.org/docs/current/static/sql-dropdatabase.html

    It can only be executed by the database owner. Also, it cannot be executed while you or anyone else are connected to the target database. (Connect to postgres or any other database to issue this command.)

    1. Have to pg_terminate_backend(pid) other connections on the db you want to drop before you drop it:

      select pg_terminate_backend(pid) from pg_stat_activity where pid <> pg_backend_pid() and datname = 'db_to_drop';