如何在 CentOS 7.9 中为 PHP 8.2 配置 pgsql 与 pdo_pgsql 扩展
如果遇到问题需要协助,请看 这里
启用 Remi 源并配置 PHP 8.2
# 安装 EPEL 和 Remi 仓库,提供 PHP 8.2 和其他现代组件
[root@localhost ~]# yum install -y epel-release
[root@localhost ~]# yum install -y https://rpms.remirepo.net/enterprise/remi-release-7.rpm
# 禁用所有已启用的remi-php仓库,避免冲突
[root@localhost ~]# yum-config-manager --disable 'remi-php*'
# 启用Remi的PHP8.2仓库
[root@localhost ~]# yum-config-manager --enable remi-php82
# 安装 PHP 8.2 及常用模块(可根据应用需求增减)
root@localhost ~]# yum install -y php php-cli php-common php-pdo php-xml
# 验证 PHP 版本是否为8.2
root@localhost ~]# php -v
PHP 8.2.20 (cli) (built: Jun 4 2024 13:22:51) (NTS gcc x86_64)
Copyright (c) The PHP Group
Zend Engine v4.2.20, Copyright (c) Zend Technologies
# 如需更换系统默认php命令版本(多版本并存场景)
root@localhost ~]# alternatives --config php
安装 PostgreSQL 扩展及客户端库
# 安装 PHP 连接 PostgreSQL 所需扩展及 PostgreSQL 客户端库
root@localhost ~]# yum install -y php-pgsql postgresql postgresql-server postgresql-contrib
# 注释: 验证 PHP 模块是否加载成功
root@localhost ~]# php -m | grep pgsql
pgsql
# 初始化 PostgreSQL 数据目录
root@localhost ~]# postgresql-setup initdb
# 启动 PostgreSQL 并设置开机启动
root@localhost ~]# systemctl restart postgresql && systemctl enable postgresql
# 设置数据库用户和测试库
切换到 postgres 用户
root@localhost ~]# su - postgres
# 注释: 进入 PostgreSQL 命令行
-bash-4.2$ psql
# 注释: 创建数据库用户和数据库
postgres=# CREATE USER zhangsan WITH PASSWORD 'aaaaaa';
postgres=# CREATE DATABASE testdb OWNER zhangsan;
# 注释: 退出 psql 和 postgres 用户
postgres=# \q
-bash-4.2$ exit
如果启用了SELinux,为避免连接被阻止,可执行:
setsebool -P httpd_can_network_connect_db 1
重启服务以使配置生效
[root@localhost ~]# systemctl restart postgresql && systemctl enable postgresql
[root@localhost ~]# systemctl restart httpd && systemctl enable httpd
创建并测试数据库连接脚本
注:如果下述test_pgsql.php中的127.0.0.1写成localhost,有时会报错
[root@localhost ~]# vim /var/www/html/test_pgsql.php
<?php
try {
$db = new PDO("pgsql:host=127.0.0.1;port=5432;dbname=testdb", "zhangsan", "aaaaaa");
echo "✅ 数据库连接成功!\n"; // 换行符在字符串里
} catch (PDOException $e) {
echo "❌ 数据库连接失败: " . $e->getMessage() . "\n"; // 换行符连接
}
?>
# 运行测试
[root@localhost ~]# php /var/www/html/test_pgsql.php
✅ 数据库连接成功!

浙公网安备 33010602011771号