raduken
raduken

Reputation: 2119

simple test php with postgresql database

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");
    ?>

Upvotes: 3

Views: 25242

Answers (2)

klin
klin

Reputation: 121474

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";
}

Upvotes: 5

Jay Blanchard
Jay Blanchard

Reputation: 34406

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';
    } 
?>

Upvotes: 13

Related Questions