0

I was wondering if anyone would be able to tell me about whether it is possible to use PHP to check if a postgresql database exists?

I am writing a PHP script and I only want it to create the database if it doesn't already exist but up to now haven't been able to see how to implement it.

Thank you


I've tried

$cmd = 'psql -U postgres -c "SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'portal';"';
    exec($cmd);

I got

PHP Parse error:  syntax error, unexpected 'portal'
2
  • \'portal\' ... but why are you using an exec rather than something like pdo? Commented Jun 21, 2016 at 15:47
  • It was a script that I'm trying to put together. :) Commented Jun 21, 2016 at 15:48

3 Answers 3

3

You have a syntax error singe the single quote is used to initalize the statement.

$cmd = 'psql -U postgres -c "SELECT schema_name FROM information_schema.schemata WHERE schema_name = \'portal\';"';
exec($cmd);

You should use PDO instead of exec, but this would probably work for you.

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

3 Comments

It doesn't return any kind of results , how do I check it ? Do you have any suggestions for me ?
If it doesn't return any results (and you know it works for another database that you can test it on), then you can go ahead and CREATE your database if the results of $cmd are empty
Or I can just use this $cmd = 'psql -U postgres -c "CREATE DATABASE IF NOT EXISTS portal;"';
1

You are confusing schema and database. in postgres it is schema what you call database in mysql. so if you want to find a database, better use pg_databases

$cmd = 'psql -U postgres -c "select \'already_there\' from pg_database where datname = \'db1\';"';
    exec($cmd);

Comments

1

It's a PHP error, you have to escape '\'portal\''

Comments

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.