PDO连接到PostgreSQL


在本教程中,我们将学习如何使用PHP PDO连接到PostgreSQL数据库服务器。

前提条件

在使用PHP PDO连接到PostgreSQL数据库服务器之前,您需要:

  • 一个PostgreSQL数据库服务器、一个示例数据库和一个可以访问该数据库的包含用户名和密码的帐户。
  • 在您的web服务器中启用了PHP PDO PostgreSQL驱动程序。

例如,我们有一个本地PostgreSQL数据库服务器,它有一个postgredb示例数据库和一个可以访问postgredb数据库的帐户,用户名和密码都是postgres。我们可以创建一个名为dbconfig.php的新数据库配置文件,并将这些数据库参数放入文件中,如下所示:

1
2
3
4
5
<?php
$host='localhost';
$db = 'postgredb';
$username = 'postgres';
$password = 'postgres';

稍后,我们将在其他脚本文件中使用require_once()函数来包含dbconfig.php配置文件,从而访问这些配置参数。

要检查PDO PostgreSQL驱动程序是否已启用,请打开php.ini文件并检查以下行是否未注释。

1
extension=php_pdo_pgsql.dll

PostgreSQL数据源名称

数据源名称或DSN传输允许您连接到数据库系统的数据库参数。PDO为不同的数据库系统定义了不同的DSN。PostgreSQL的数据源名称由以下参数组成:

  • DNS前缀:pgsql:
  • host:PostgreSQL数据库所在的数据库服务器的主机名。
  • port:PostgreSQL数据库运行的端口,默认端口为5432。
  • dbname:数据库名称。
  • user:连接到数据库dbname的用户的名称。您可以在DSN或PDO类的构造函数中指定用户名。
  • password:用户名的密码。可以在DSN或PDO构造函数中指定密码。

请注意,如果将PDO构造函数中的用户名和密码放入数据源名称(DSN)中,PDO会忽略它们。

下面的DSN允许我们连接到本地PostgreSQL数据库服务器中的postgredb数据库。

1
pgsql:host=localhost;port=5432;dbname=postgredb;user=postgres;password=postgres

连接到PostgreSQL

以下代码说明如何连接到PostgreSQL数据库服务器中的postgredb数据库:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
 
require_once 'dbconfig.php';
 
$dsn = "pgsql:host=$host;port=5432;dbname=$db;user=$username;password=$password";
 
try{
// 创建PostgreSQL数据库连接
$conn = new PDO($dsn);
 
// 如果成功连接到PostgreSQL,则显示消息
if($conn){
echo "成功连接到数据库 <strong>$db</strong> !";
}
}catch (PDOException $e){
// 报告错误消息
echo $e->getMessage();
}

如果所有设置都正确,您将看到以下消息:

1
成功连接到数据库 postgredb


原文链接:https://codingdict.com/