Ubuntu 下 pgAdmin 与 PHP 连接 PostgreSQL 的完整方法
一 环境准备与安装
- 安装数据库与工具(PostgreSQL 与 pgAdmin 4):
- 更新索引并安装:sudo apt update && sudo apt install postgresql postgresql-contrib pgadmin4
- 启动并设置开机自启:sudo systemctl start postgresql && sudo systemctl enable postgresql
- 为 postgres 用户设置密码:sudo -u postgres psql -c “ALTER USER postgres WITH PASSWORD ‘your_password’;”
- 安装 PHP 的 PostgreSQL 扩展(用于 PHP 连接 PG):sudo apt install php-pgsql
- 如使用 Apache:sudo systemctl restart apache2
- 如使用 Nginx + PHP-FPM:sudo systemctl restart php-fpm && sudo systemctl restart nginx
- 验证扩展是否生效:php -m | grep -E ‘pgsql|pdo_pgsql’(应看到 pgsql 与 pdo_pgsql)
- 说明:本节的 pgAdmin 指 pgAdmin 4(桌面/服务器模式均可),PHP 连接使用 php-pgsql 扩展提供的驱动
二 使用 pgAdmin 4 连接 PostgreSQL
- 桌面模式:
- 在应用菜单启动 pgAdmin 4,首次登录设置邮箱与密码
- 左侧 Servers → Create → Server,General 填写名称;Connection 填写:
- Host name/address:localhost(或服务器 IP)
- Port:5432
- Username:postgres
- Password:上面设置的密码
- Save 后即可管理数据库对象与执行查询
- 服务器模式(Web 方式,Nginx + Gunicorn/uWSGI):
- 安装依赖与 pgAdmin 4(建议 Python 虚拟环境),配置会话/存储/日志目录权限
- 使用 Gunicorn 启动 pgAdmin WSGI 应用,并以 Nginx 反向代理(常见为 UDS 或 socket)
- 浏览器访问域名或服务器 IP,登录后在 Server 中按上述 Connection 参数添加 PostgreSQL
三 使用 PHP 连接 PostgreSQL
- 原生驱动(pg_connect):
- PDO(推荐,支持异常与预处理):
- 代码示例:
-
PDO::ERRMODE_EXCEPTION]);
echo "连接成功";
// 查询示例:$pdo->query("SELECT version()")->fetchColumn();
} catch (PDOException $e) {
echo "连接失败: " . $e->getMessage();
}
?>
- 要点:
- 确保已安装并启用 php-pgsql(含 pdo_pgsql)
- 连接参数(host/port/dbname/user/password)需与 PostgreSQL 实际配置一致
- 生产环境不要将凭据硬编码,建议使用环境变量或受控配置文件
四 常见问题与排查
- 服务与端口:
- 确认 PostgreSQL 运行:sudo systemctl status postgresql
- 默认端口 5432 未被占用:ss -lntp | grep 5432
- 远程访问(如 PHP 与 PG 不在同一台机器):
- 修改 PostgreSQL 认证与监听(示例,具体路径因版本而异,如 /etc/postgresql/*/main/pg_hba.conf 与 postgresql.conf):
- 允许远程主机的 MD5 认证:host all all 0.0.0.0/0 md5
- 取消或调整 listen_addresses(如:listen_addresses = ‘*’),并重启数据库
- 防火墙放行:sudo ufw allow 5432/tcp
- pgAdmin 无法登录或页面异常:
- 若使用 phpPgAdmin(旧项目),常见为关闭额外登录安全:编辑 config.inc.php,将 $conf[‘extra_login_security’] 设为 false;并确保 PostgreSQL 的 pg_hba.conf 已允许密码登录
- 若使用 pgAdmin 4,优先检查账号密码、主机可达性与服务状态
- PHP 报错“could not find driver”或未定义函数:
- 安装并启用 php-pgsql,重启 Web 服务(Apache 或 PHP-FPM)后重试
- 日志定位:
- PostgreSQL 日志(如 /var/log/postgresql/)与 Web/PHP 错误日志可快速定位认证与连接问题