simple test php with postgresql database

19,604

Solution 1

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

Solution 2

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";
}
Share:
19,604
raduken
Author by

raduken

Updated on June 14, 2022

Comments

  • raduken
    raduken almost 2 years

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