3

I am using this php to test if I am connected in a postgree database, works very well, but how can I insert a error Message and a Message showing the database is connected and not connected?

Example: like: You are connect to:database_name

or:

You could not connect to:database_name

That is my code:

<?php
    $connection = pg_connect ("host=localhost dbname=site user=postgres password=root");
    ?>

2 Answers 2

14

Just test the truthiness of the connection:

<?php
    $connection = pg_connect ("host=localhost dbname=site user=postgres password=root");
    if($connection) {
       echo 'connected';
    } else {
        echo 'there has been an error connecting';
    } 
?>
Sign up to request clarification or add additional context in comments.

Comments

5

Return value of pg_connect() is

PostgreSQL connection resource on success, FALSE on failure.

so check this value:

if (!$connection = pg_connect ("host=localhost dbname=site user=postgres password=root")) {
    $error = error_get_last();
    echo "Connection failed. Error was: ". $error['message']. "\n";
} else {
    echo "Connection succesful.\n";
}

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.