简单的测试PHP与postgresql数据库


simple test php with postgresql database

我使用这个php来测试我是否连接在postgree数据库中,工作得很好,但是我怎么能插入一个错误消息和一个显示数据库连接和未连接的消息?

的例子:例如:您正在连接到:database_name

或:

您无法连接到:database_name

这是我的代码:

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

测试连接的真实性:

<?php
    $connection = pg_connect ("host=localhost dbname=site user=postgres password=root");
    if($connection) {
       echo 'connected';
    } else {
        echo 'there has been an error connecting';
    } 
?>

pg_connect()的返回值为

PostgreSQL连接资源成功,失败FALSE。

所以检查这个值:

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