分类: PostgreSQL
一段检测php8能否链接上PostgreSQL数据库的脚本代码 - PostgreSQL

修改下面的数据库地址,端口账号等信息,会显示PostgreSQL数据库版本信息,如链接失败则给出提示,使用的是PHP PDO PostgreSQL驱动.

<?php
$host='localhost';
$db = 'dbname';
$port = '5432';
$username = 'dbuser';
$password = 'youpassword';
  
$dsn = "pgsql:host=$host;port=$port;dbname=$db;user=$username;password=$password";
  
try{
    // 创建PostgreSQL数据库连接
    $conn = new PDO($dsn);
     
    // 如果成功连接到PostgreSQL,则显示消息
    if($conn){
        $result = $conn->query("SELECT version()");
        $version = $result->fetchColumn();
        
        echo "成功连接到数据库 <strong>$db</strong>!<br>";
        echo "当前的PostgreSQL版本为:$version";
    }
}catch (PDOException $e){
	// 转换错误消息为UTF-8字符集
    $errorMessage = iconv('GBK', 'UTF-8', $e->getMessage());
    // 报告错误消息
    echo $errorMessage;

}

运行结果如下:

成功连接到数据库 testdb!
当前的PostgreSQL版本为:PostgreSQL 16.0 on x86_64-pc-linux-gnu, compiled by gcc.real (Debian 10.2.1-6) 10.2.1 20210110, 64-bit

相关博文:

已有 3 条评论
  1. 太上感应篇

    来这里学习一下 <br> <br>
    太上感应篇 回复
  2. Geri Mowle

    Hello, <br> <br>Your business listing on dbanote.com and wanted to make sure your details are up to date. <br> <br>Unclaimed listings miss out on local traffic and vital search authority. <br> <br>You can use our platform to claim your spot and instantly push your updated business info out to hundreds of directories in seconds. <br> <br>Verify your business page here: <br>directoryinspector.com/dbanote.com <br> <br>No cost or catches to get set up. <br> <br>Best, <br>Geri Mowle
    Geri Mowle 回复
  3. Uta Clem

    Hello, <br> <br>I came across dbanote.com and thought this might be useful. Is getting more traffic something you're working on? <br> <br>I help out at Vantovo. We match websites with visitors already interested in what they offer from a network of thousands of partner sites. You set your keywords and target a country, state, city or zip code, and the system handles the rest. <br> <br>You can try it free for 7 days with up to 7,000 targeted visitors a day, with no long-term commitment. <br> <br>You can start the trial: https://shorter.me/IJQk4
    Uta Clem 回复
发表评论
💡 支持 Markdown 语法