使用PDO操作PostgreSQL数据库

通过源码安装相关扩展(温馨提示:下载源码时请选择和当前环境相同的版本)
[root@localhost src]# wget https://www.php.net/distributions/php-*.*.*.tar.gz
[root@localhost src]# tar -xf php-*.*.*.tar.gz
 
安装pgsql扩展
[root@localhost src]# cd php-*.*.*/ext/pgsql/
[root@localhost pgsql]# /program/php/bin/phpize
[root@localhost pgsql]# ./configure --with-php-config=/program/php/bin/php-config
[root@localhost pgsql]# make && make install
 
安装pdo_pgsql扩展
[root@localhost pgsql]# cd ../pdo_pgsql/
[root@localhost pdo_pgsql]# /program/php/bin/phpize
[root@localhost pdo_pgsql]# ./configure --with-php-config=/program/php/bin/php-config
[root@localhost pdo_pgsql]# make && make install
 
启用pgsql扩展和pdo_pgsql扩展
[root@localhost pgsql]# vim /program/php/php.ini
extension=pdo_pgsql
extension=pgsql
[root@localhost pgsql]# service php-fpm restart



使用PDO操作PostgreSQL数据库的简单示例代码

<?php
declare(strict_types=1);
ini_set('display_errors', 'On');
error_reporting(-1);

$driver = 'pgsql'; // 使用pgsql驱动
$host = 'localhost';
$dbname = 'testdb';
$schema = 'private';
$username = '账号';
$password = $password ?? '密码';

$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false,
];

$pdo = new PDO("$driver:host=$host;dbname=$dbname", $username, $password, $options);

$query = "SELECT \"name\", \"gender\", \"birth\" FROM \"$schema\".\"prefix_user\" WHERE \"uid\" = :uid LIMIT 1";
echo $query . PHP_EOL; // SELECT "name", "gender", "birth" FROM "private"."prefix_user" WHERE "uid" = :uid LIMIT 1

$sth = $pdo->prepare($query);

$params = ['uid' => 3];
foreach ($params as $field => $value) {
    $sth->bindValue(":$field", $value);
}

$sth->execute();

$fetchAll = $sth->fetchAll();

$row = $fetchAll[0] ?? [];
if ($row) {
    $name = $row['name'];
    $gender = $row['gender'];
    $birth = $row['birth'];
    echo "俺叫{$name}{$gender}),出生于{$birth}年。"; // 俺叫张三(男),出生于2003年。
}

Copyright © 2024 码农人生. All Rights Reserved