将我的PHP中的数据库连接从mysql更改为Postgres

时间:2019-06-12 16:27:01

标签: php mysql database postgresql

我需要更改php连接才能与postgres一起使用

<?php

    define('SPHOST','localhost');
    define('SPUSER','jason');
    define('SPPASS','A123456a');
    define('SPDB','admin_plus');

    $sp=new mysqli(SPHOST,SPUSER,SPPASS,SPDB);

    if($sp->connect_errno){
        echo "Check Host Connection<br/>";
    }
?>

1 个答案:

答案 0 :(得分:3)

您可以像这样使用PDO创建postgress连接:

<?php

$host='localhost';
$db = 'admin_plus';
$username = 'jason';
$password = 'A123456a';

$dsn = "pgsql:host=$host;port=5432;dbname=$db;user=$username;password=$password";

try{
    // create a PostgreSQL database connection
    $conn = new PDO($dsn);

    // display a message if connected to the PostgreSQL successfully
    if($conn){
        echo "Connected to the <strong>$db</strong> database successfully!";
    }
}catch (PDOException $e){
     // report error message
     echo $e->getMessage();
}

确保已启用php_pdo_pgsql扩展名。