带有 postgresql 数据库的简单测试 php
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32700618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
simple test php with postgresql database
提问by raduken
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?
我正在使用此 php 来测试我是否已连接到 postgree 数据库中,效果很好,但是如何插入错误消息和显示数据库已连接和未连接的消息?
Example: like: You are connect to:database_name
示例:例如:您正在连接到:database_name
or:
或者:
You could not connect to:database_name
您无法连接到:database_name
That is my code:
那是我的代码:
<?php
$connection = pg_connect ("host=localhost dbname=site user=postgres password=root");
?>
回答by Jay Blanchard
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';
}
?>
回答by klin
Return value of pg_connect()
is
的返回值pg_connect()
是
PostgreSQL connection resource on success, FALSE on failure.
成功时为 PostgreSQL 连接资源,失败时为 FALSE。
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";
}